三数之和java

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    
    
    public List<List<Integer>> threeSum(int[] nums) {
    
    
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int n : nums){
    
    
            map.put(n,map.getOrDefault(n,0)+1);
        }
        
        for(int i = 0;i< nums.length-2;++i){
    
    
            if(i > 0 && nums[i] == nums[i - 1]){
    
    //不计算重复的
                continue;
            }
            for(int j = i + 1;j<nums.length;j++){
    
    
                int tmp = -nums[j]-nums[i];//其实这里就等于a+b+c=0
                //我的理解是,假设abc不同,那么她们的组合有多种,这里我们只取其中一种,递增所以就有下面这个if
                if(tmp < nums[j]){
    
    
                    continue;
                }
                if(map.containsKey(tmp)){
    
    
                    //三个元素相同,都是0
                    if(nums[i] == 0 && nums[j] == 0 && map.get(0) < 3){
    
    
                        continue;
                    }
                    //两个元素相同,如 -2 1 1
                    if(nums[j] == tmp && map.get(tmp) < 2){
    
    
                        continue;
                    }
                    //正常情况
                    if(!res.isEmpty() //可能出现和上一个相同的情况,虽然i进行了判断解决了,但是j没有进行解决
                    && res.get(res.size()-1).get(1) == nums[j] 
                    && res.get(res.size()-1).get(0) == nums[i]){
    
    
                        continue;
                    }
                    List<Integer> array = new ArrayList<Integer>();
                    array.add(nums[i]);
                    array.add(nums[j]);
                    array.add(tmp);
                    res.add(array);
                }
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43824233/article/details/111475982