3Sum

来源:互联网 发布:数据恢复多少钱 编辑:程序博客网 时间:2024/06/06 12:50

题目描述:
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:
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)

这里和前面的Two Sum是一个思路,用两个指针往里靠拢,只是多个n次遍历而已。
必须得到不能重复的值,我这里用了set集合,如果重复检查,继续下一次遍历。

public List<List<Integer>> threeSum(int[] nums) {    Arrays.sort(nums);    List<List<Integer>> result=new ArrayList<List<Integer>>();    Set<Integer> set =new HashSet<Integer>();    for (int i = 0; i < nums.length; i++) {        if(!set.contains(nums[i])){            set.add(nums[i]);            int low=i+1,high=nums.length-1;            while(low<high){                if(nums[low]+nums[high]==0-nums[i]){                    List<Integer> list=new ArrayList<Integer>();                    list.add(nums[i]);                    list.add(nums[low]);                    list.add(nums[high]);                    result.add(list);                    //这段循环条件是比较细节的地方,要注意                    while(nums[low]==nums[low+1]&&low+1<high){                        low++;                        continue;                    }                    low++;                }else if(nums[low]+nums[high]<0-nums[i]){                    low++;                }else{                    high--;                }            }        }    }    return result;}
0 0