LC454-四數相加
阿新 • • 發佈:2022-04-09
給你四個整數陣列 nums1、nums2、nums3 和 nums4 ,陣列長度都是 n ,請你計算有多少個元組 (i, j, k, l) 能滿足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
示例:
輸入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
輸出:2
解釋:
兩個元組如下:
- (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
思路:
假如是陣列A,B,C,D
- 首先定義 一個Hashmap,key放a和b兩數之和,value 放a和b兩數之和出現的次數。
- 遍歷大A和大B陣列,統計兩個陣列元素之和,和出現的次數,放到map中。
- 定義int變數count,用來統計 a+b+c+d = 0 出現的次數。
- 在遍歷大C和大D陣列,找到如果 0-(c+d) 在map中出現過的話,就用count把map中key對應的value也就是出現次數統計出來。
- 最後返回統計值 count 就可以了
注:使用暴力破解用四個for迴圈那可太慢了,萬一陣列元素多指不定還超時,因此這個方法不適用。
class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { Map<Integer,Integer> map=new HashMap<>(); int count=0; int temp; //存放兩數之和,後面作為key for(int i:nums1){ for(int j:nums2){ temp=i+j; if(map.containsKey(temp)) { map.put(temp,map.get(temp)+1); } else{ map.put(temp,1); //如果沒有這個key則儲存值為1 } } } for(int i:nums3){ for(int j:nums4){ temp=i+j; if(map.containsKey(0-temp)) { count+=map.get(0-temp); } } } return count; } }