給定一個(gè)包含 n 個(gè)整數(shù)的數(shù)組 nums,判斷 nums 中是否存在三個(gè)元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重復(fù)的三元組。
注意:答案中不可以包含重復(fù)的三元組。
例如, 給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list2 = new ArrayList<List<Integer>>();
// 判斷給定數(shù)組是否存在三個(gè)及以上元素
if(nums.length >= 3){
// 對(duì)數(shù)組排序并放入HashMap中
Arrays.sort(nums);
Map<Integer,Integer> map = new HashMap<>();
for(int i =0; i<nums.length;i++){
map.put(nums[i],i);
}
List<Integer> list = null;
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
int c = 0-nums[i]-nums[j];
// 判斷mapKey值是否存在使三數(shù)相加為零,且下標(biāo)大于j
if(map.containsKey(c) && map.get(c) > j){
list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(c);
if(!list2.contains(list)){
list2.add(list);
}
}
}
}
}
return list2;
}