码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode][15] 3Sum

时间:2018-09-09 21:08:08      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:amp   arrays   指针   pre   去重   选择   triplets   length   integer   

15. 3Sum

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

解析

从给定的数组里面找到三个数之和等于0,返回所有的结果集,去重。

参考答案(没做出来)

public List<List<Integer>> threeSum(int[] num) {
    Arrays.sort(num);
    List<List<Integer>> res = new LinkedList<>(); 
    for (int i = 0; i < num.length-2; i++) {
        if (i == 0 || (i > 0 && num[i] != num[i-1])) {
            int lo = i+1, hi = num.length-1, sum = 0 - num[i];
            while (lo < hi) {
                if (num[lo] + num[hi] == sum) {
                    res.add(Arrays.asList(num[i], num[lo], num[hi]));
                    while (lo < hi && num[lo] == num[lo+1]) lo++;
                    while (lo < hi && num[hi] == num[hi-1]) hi--;
                    lo++; hi--;
                } else if (num[lo] + num[hi] < sum) lo++;
                else hi--;
           }
        }
    }
    return res;
}

这里主要是去重比较麻烦,所以这里选择了先排序,然后用双指针遍历,再把相邻重复的元素的忽略掉。

[leetcode][15] 3Sum

标签:amp   arrays   指针   pre   去重   选择   triplets   length   integer   

原文地址:https://www.cnblogs.com/ekoeko/p/9614972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!