LeetCode 15. 3Sum(双指针)

题目来源:https://leetcode.com/problems/3sum/

问题描述

15. 3Sum

Medium

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

 

A solution set is:

[

  [-1, 0, 1],

  [-1, -1, 2]

]

Accepted

490K

Submissions

2.1M

Seen this question in a real interview before?

------------------------------------------------------------

题意

给出一组整数序列,求序列中这样的三个数组成的集合,三个数的和为0.

------------------------------------------------------------

思路

问题可以转化为给定一个数a,求序列中另外两个数b, c,使得b + c = -a.

将输入无序序列排序,对于序列中的每个a,问题转化为求a右侧的数对,使得数对的和为-a. 有序序列求零和数对有经典算法双指针法可以用O(n)解决,这样复杂度是O(n^2)。再加上对输入的无序序列排序的时间O(nlogn),总的复杂度还是O(n^2).

------------------------------------------------------------

代码

class Solution {
    /**
    Go through #n element:
        double-pointer for contrary sum of the i-th element: O(n)
    Total: O(n^2)
    **/
    public List<List<Integer>> threeSum(int[] nums) {
        int i = 0, n = nums.length, left = 0, right = n - 1, sum = 0;
        if (n < 3)
        {
            return new LinkedList<>();
        }
        Arrays.sort(nums);
        LinkedList<List<Integer>> ret = new LinkedList<>();
        for (i=0; i<n-2; i++)
        {
            if (i > 0 && nums[i] == nums[i-1])
            {
                continue;
            }
            left = i + 1;
            right = n - 1;
            while (left < right)
            {
                sum = nums[left] + nums[right];
                if (sum == -nums[i])
                {
                    LinkedList<Integer> list = new LinkedList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ret.add(list);
                    while (left < n-1 && nums[left] == nums[++left]);
                }
                else if (sum < -nums[i])
                {
                    while (left < n-1 && nums[left] == nums[++left]);
                }
                else
                {
                    while (right > 0 && nums[right] == nums[--right]);
                }
            }
        }
        return ret;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值