15. 3Sum

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
      Arrays.sort(nums);
      List<List<Integer>> result = new ArrayList<>();
      for(int i = 0; i < nums.length - 2; i++){
        if( i == 0 || i > 0 && nums[i] != nums[i-1]){
          int j = i+1, k = nums.length - 1, sum = 0 - nums[i];
          while(j < k){
            int current_sum = nums[j] + nums[k];
            if(current_sum == sum){
              result.add(Arrays.asList(nums[i], nums[j], nums[k]));
              while(j < k && nums[j] == nums[j+1]) j++;
              while(j < k && nums[k] == nums[k-1]) k--;
              j++;
              k--;
            }else if (current_sum < sum){
              j++;
            }else{
              k--;
            }
          }
        }
      }
      return result;
        
    }
}

 3 sum with/ without deduplication 3sum FB超级喜欢问这道题,所以务必sort和hash table的解法都烂熟于心,也问了时间和空间复杂度。4sum hashmap

 

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

posted on 2018-07-18 08:28  猪猪&#128055;  阅读(112)  评论(0)    收藏  举报

导航