Given an array nums containing n integers, determine whether there are three elements a, b, c in nums, such that a + b + c = 0? Please find all triples that meet the conditions and are not repeated.
Note: The answer cannot contain repeated triples.
Example:
Given the array nums = [-1, 0, 1, 2, -1, -4],
The set of triples that meet the requirements are:
[
[-1, 0, 1],
[-1, -1, 2]
]
Source: LeetCode
Link: https://leetcode-cn.com/problems/3sum
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
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;
}
}