3Sum

来源:互联网 发布:双十一大学生网购数据 编辑:程序博客网 时间:2024/04/29 16:28

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: 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]]


注意两个去重的地方

代码:

public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> result = new ArrayList<>();        if(nums == null || nums.length == 0) return new ArrayList<>();        Arrays.sort(nums);        for(int i=0;i<nums.length;i++){            if( i != 0 && nums[i] == nums[i-1]) continue;            int low = i+1;            int high = nums.length-1;            while(low<nums.length && low<high){                int sum = nums[low] + nums[high];                //System.out.println(sum);                if(sum == -nums[i]){                    List<Integer> ret = new ArrayList<>();                    ret.add(nums[i]);                    ret.add(nums[low]);                    ret.add(nums[high]);                    result.add(ret);                    high--;                    low++;                    while(low < high && nums[low] == nums[low-1]){                        low++;                    }                    while(low < high && nums[high] == nums[high+1]){                        high--;                    }                }                if(sum > -nums[i]){                    high--;                }                if(sum < -nums[i]){                    low++;                }            }        }        return result;    }


0 0
原创粉丝点击