Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1973 from Projecthappy/master
Browse files Browse the repository at this point in the history
优化0454.四数相加II中 java的方法
  • Loading branch information
youngyangyang04 authored Apr 6, 2023
2 parents 27ae005 + 6dd7f42 commit 2ff490e
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions problems/0454.四数相加II.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,26 +97,25 @@ Java:
```Java
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap<>();
int temp;
int res = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//统计两个数组中的元素之和,同时统计出现的次数,放入map
for (int i : nums1) {
for (int j : nums2) {
temp = i + j;
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
int tmp = map.getOrDefault(i + j, 0);
if (tmp == 0) {
map.put(i + j, 1);
} else {
map.put(temp, 1);
map.replace(i + j, tmp + 1);
}
}
}
//统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
for (int i : nums3) {
for (int j : nums4) {
temp = i + j;
if (map.containsKey(0 - temp)) {
res += map.get(0 - temp);
int tmp = map.getOrDefault(0 - i - j, 0);
if (tmp != 0) {
res += tmp;
}
}
}
Expand Down

0 comments on commit 2ff490e

Please sign in to comment.