LeetCode 15 3Sum 找出数组里面3个数的和等于指定值。

来源:互联网 发布:北京折叠知乎 编辑:程序博客网 时间:2024/06/05 07:11

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)
翻译: 给一个数组。找出其中3个数字等于0的组合。 按升序排列。

思路:这道题和前些天刷的Two Sum 原理差不多。只不过是Two Sum的和是前一个数字的相反数。还有一个问题就是,如果当前数字和下一个数字重复,应该排除这些重复,不遍历,减少复杂度。

代码:

public static ArrayList<ArrayList<Integer>> threeSum(int[] num){ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();if(num == null||num.length<3)//如果只有2个数字 或者为空 返回空return res;Arrays.sort(num);for(int i = 0; i<num.length -2;i++)// 保证最后得有num.length-1 和num.length-2两个数,才可以进循环{if(i > 0 && num[i] == num[i-1])//如果要是有重复的直接跳过。continue;ArrayList<ArrayList<Integer>> cur = twoSum(num,i+1,-num[i]); //得到当前数字可以组合出来的数字序列的子集。res.addAll(cur);}return res;            }    public static ArrayList<ArrayList<Integer>>twoSum (int []num,int start,int target)    {        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();     if(num == null||num.length < 2)    return res;    int l = start;//起始位置    int pri = start-1;//当前数字    int r = num.length-1;//终止位置    while(l < r)//采用夹逼,逼近target    {    if(num[l]+num[r] == target)//    {    ArrayList<Integer> te = new ArrayList<Integer>();//符合的话 把三个数放入到list中    te.add(num[pri]);    te.add(num[l]);    te.add(num[r]);    res.add(te);    int k = l + 1;//从l的下一个开始 去除重复。    while(k < r&& num[k] == num[l])    k++;    l = k;    k = r - 1;//去除R的重复    while(k > l &&num[k] == num[r])    k--;    r = k;    }    else if(num[l] + num[r] > target)//夹逼    r--;    else l++;        }    return res;        }
如果要是求4 sum的话 直接可以在写个函数求出3 sum的 然后在整合到4sum中。原理其实差不多。

更好的办法,还有待考虑。

0 0
原创粉丝点击