1. 两数之和
Accept
可用map.containsKey()
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = Arrays.asList(2, 7, 11, 15);
int target = 9;
List<Integer> res = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
map.put(list.get(i),i);
}
for (int i = 0; i < list.size(); i++) {
int temp = target - list.get(i);
if (map.getOrDefault(temp, null) != null){
res.add(i);
res.add(map.get(temp));
break;
}
}
System.out.println(res);
}
}
第454题.四数相加II
accept
时间复杂度高了 为 3次方
public class test {
public static void main(String[] args) {
int a[]= {1, 2};
int b[]= {-2,-1};
int c[]= {-1, 2};
int d[]= { 0, 2};
Set<Integer> hash = new HashSet<>();
for(int t : d){
hash.add(t);
}
int sum = 0;
for (int j : b) {
for (int k : a) {
for (int value : c) {
if (hash.contains(-(j + k + value))) {
sum++;
}
}
}
}
System.out.println(sum);
}
}
可改成 2次方复杂度–双for循环:
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int res = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//统计两个数组中的元素之和,同时统计出现的次数,放入map
for (int i : nums1) {
for (int j : nums2) {
int sum = i + j;
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
}
//统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
for (int i : nums3) {
for (int j : nums4) {
res += map.getOrDefault(0 - i - j, 0);
}
}
return res;
}
}

被折叠的 条评论
为什么被折叠?



