leetcode-15-3sum

在数组中找三个数字,使它们的和为0  :  https://leetcode.com/problems/3sum      


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


在数组中找三个数字,使它们的和为0, 找出所有这样的三个数,不能重复   开始想像2sum一样从两头向中间扫,找和为当前 数组值 的相反数. 最后set去重 二将当前数组存到map中, 再对数组元素两两求和找相反数,4sum的办法,最后set去重   。。。。去重失败 题解还是用的2sum的办法,跳过相等的数从而跳过重复结果.    看来不要老是想着用set去重…  

    class Solution {
       public List<List<Integer>> threeSum(int[] nums) {
           Arrays.sort(nums);
           List<List<Integer>> res = new ArrayList();
           int len = nums.length;
           for(int i = 0; i < len-2; i++){
               if(i == 0 || nums[i] != nums[i-1]){   //跳过查找与上一个数相等的数,因为它们结果一样
                   int sum = 0-nums[i];
                   int lo = i+1;
                   int hi = len-1;
                   while(lo < hi){
                       int t = nums[lo] + nums[hi];
                       if(t == sum){
                           res.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
                           while(lo < hi && nums[lo] == nums[lo+1]) lo++;
                           while(lo < hi && nums[hi] == nums[hi-1]) hi--;
                           //这两个while也是跳过所有与当前结果相同的数。
                           lo++;
                           hi--;
                       }
                       else if(t < sum)
                           lo++;
                       else
                           hi--;
                   }
               }
           }
           return res;
       }
    }
0

Powered by Jekyll and Theme by solid