class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//第二种思路,利用hashmap,将三数之和转换为两个数之和等于第三个数,这样利用两重循环,就遍历,最后求出第三个数是否存在map里面如果存在就满足条件。
HashSet<List<Integer>> hashSet=new HashSet<>();
HashMap<Integer,Integer> map=new HashMap<>();
for (int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for (int i=0;i<nums.length-1;i++){
for (int j=i+1;j<nums.length;j++){
int c=0-nums[i]-nums[j];
//map中包含c,但是c对应的下标并不是i,也不是j
if (map.containsKey(c)&&i!=map.get(c)&&j!=map.get(c)){
List<Integer> list=new LinkedList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(c);
//就是在加之前排序一下,这样方便集合去重
Collections.sort(list);
hashSet.add(list);
}
}
}
List<List<Integer>> rs=new ArrayList<>(hashSet);
return rs;
}
}
Leetcode は 3 つの数値の合計を求めます
おすすめ
転載: blog.csdn.net/yang12332123321/article/details/120846084
おすすめ
ランキング