需求
输出输出
思考
如果用三个for遍历的话,会出现时间复杂度是O(n的3次方)
考虑使用两层for确定2个数,第三个数在哈希表中确定是否有。
Java代码:
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
/*思考:如果只用set的话,我们无法判断例如(-1,-1,2)这种数据在(-1,2)确定,
另一个-1是否选取的问题(故使用Map记录下标) //存入元素到map*/
HashSet<ArrayList<Integer>> set = new HashSet<>();
HashMap<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
//遍历确定2个,在哈希表查另一个
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (map.containsKey(-(nums[i] + nums[j])) &&
map.get(-(nums[i] + nums[j])) != i && map.get(-(nums[i] + nums[j])) != j) {
ArrayList<Integer> cur = new ArrayList<Integer>();
cur.add(nums[i]);
cur.add(nums[j]);
cur.add(0 - nums[i] - nums[j]);
Collections.sort(cur);
set.add(cur);
}
}
}
//把Set转为List
List<List<Integer>> lis = new ArrayList<>();
for(ArrayList<Integer> c:set){
lis.add(c);
}
return lis;
}
}
输出:

原文:https://www.cnblogs.com/jiyongjia/p/13380874.html