Leetcode 15. 3sum

@author stormma
@date 2017/11/03


生命不息,奋斗不止!


题目

Given an array S of n integers, are there elements a, b, c in S 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.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

思路分析

刚开始我使用确定两个数去二分查找另外一个数,这样时间复杂度是O(N^2long N),但是有个问题就是不好去重,这个着实让我很纠结,然后思路一下被限制了。查看leetcode discuss之后,看到人家的答案豁然开朗。

我们换个思路,这次确定一个值,然后two pointer去查找另外两个元素,把sum = 0的全部添加进来,然后确定下一个元素的时候,我们跳过和之前一样的元素,这样时间复杂度O(N^2),而且去重还贼简单(看了别人的答案,我反手给自己一巴掌,实在太智障)。

  1. for i 0 to length - 2
  2. two pinter查找sum = 0 - nums[i]如果相等,添加答案,并且skip重复的元素
  3. 如果不相等,判断与0 - nums[i]的大小,然后移动指针即可

代码实现

static class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> ans = new ArrayList<>();
            if (nums.length < 3) {
                return ans;
            }

            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 2; i++) {
                // the min elemment > 0, break
                if (nums[i] > 0) {
                    break;
                }
                // skip repeat element
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;
                }
                int low = i + 1, high = nums.length - 1, target = 0 - nums[i];
                while (low < high) {
                    if (target < nums[low] + nums[high]) {
                        high--;
                    } else if (target > nums[low] + nums[high]) {
                        low++;
                    } else {
                        ans.add(Arrays.asList(nums[i], nums[low], nums[high]));
                        //eg: -2 0 0 1 1 2 2 and skip repeating elements, and their sum equals target
                        while (low < high && nums[low + 1] == nums[low])  {
                            low++;
                        }
                        while (low < high && nums[high - 1] == nums[high]) {
                            high--;
                        }
                        low++;
                        high--;
                    }
                }
            }
            return ans;
        }
    }

代码很简单,相信你一看就懂,实在不懂,就再看一遍。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值