Leetcode.15 3Sum

Leetcode.15 3Sum

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

Solution

集合法

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        return threeSum(nums,0);
    }
    private List<List<Integer>> threeSum(int[] nums, int target){
        Arrays.sort(nums);
        Set<List<Integer>> res = new HashSet<>();
        for(int i=0;i<nums.length;i++){
            // target - nums[i]
            Map<Integer,Integer> map = new HashMap<>();
            for(int j=i+1;j<nums.length;j++){
              //变为two sum
                if(map.containsKey(target - nums[i]-nums[j])){
                    List<Integer> l = new ArrayList<>();
                    l.add(nums[i]);
                    l.add(nums[map.get(target - nums[i]-nums[j])]);
                    l.add(nums[j]);
                    res.add(l);
                }
                map.put(nums[j],j);
            }
        }
        return new ArrayList<>(res);
    }
    
}

指针+集合

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        return threeSum(nums,0);
    }
    private List<List<Integer>> threeSum(int[] nums, int target){
        Arrays.sort(nums);
        Set<List<Integer>> res = new HashSet<>();
        int l = 0;        
        while(l<nums.length-2){
            int m = l+1;
            int sum = target - nums[l];
            int k = nums.length - 1;
            while(m < k){
                if(nums[m] + nums[k] == sum){
                    res.add(Arrays.asList(nums[l],nums[m],nums[k]));
                    while(m<k && nums[m] == nums[m+1]){
                        m++;
                    }
                    while(m<k && nums[k] == nums[k-1]){
                        k--;
                    }
                    m++;
                    k--;
                    
                }else if(nums[m] + nums[k] > sum){
                    k--;
                }else{
                    m++;
                }
            }
            l++;
        }
        return new ArrayList<>(res);
    }
    
}
posted @ 2020-08-17 16:21  mhp  阅读(109)  评论(0)    收藏  举报