本文知识点: HashTable
推荐阅读前置知识:
-----------------------------
记得做Leetcode第一题两数相加,点开leetcode评论区:
“有人相爱,有人夜里看海,有人leetcode第一题写不出来。”
现在我是四数之和做不出来。
其实会做两数之和, 四数之和的难点倒是没什么难点,基本思路是一样的:
1. 使用HashMap储存
Key: 和两数之和一样,是值
Value: 和两数之和不一样的地方: 出现的次数;
为什么要储存出现的次数? 因为题目中需要返回的是 四数相加等于0 的次数。
刚开始做题的时候我陷入了困惑。四个数要怎么办?
请看代码!
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int count = 0;
//其实把他看成两数之和,先把两个数加起来,sum为key, 出现次数为value存成一个Hashtable;
for(int i : nums1){
for(int j : nums2){
if(table.containsKey(i+j)){
int num = table.get(i+j);
table.put(i+j, num+1);
}else{
table.put(i+j,1);
}
}
}
//这时候把另外两个数num3, num4相加。 找里面有没有 0 - sum的值
for(int i : nums3){
for(int j : nums4){
if(table.containsKey(0-(i+j))){
//注意因为要返回符合条件的次数,这里需要用到储存的value (排列组合)
count += table.get(0-(i+j));
}
}
}
return count;
}
}