454. 四数相加 II - 力扣(Leetcode)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import java.util.Map; import java.util.HashMap;
public class FourSumII454 { public static void main(String[] args) { int[] nums1 = {1,2}; int[] nums2 = {-2,-1}; int[] nums3 = {-1,2}; int[] nums4 = {0,2}; System.out.println(new Solution().fourSumCount(nums1,nums2,nums3,nums4)); } }
class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int res = 0; Map<Integer,Integer> map = new HashMap<>(); for (int num01 : nums1) { for (int num02 : nums2 ) { int sum01 = num01 + num02; if (map.containsKey(sum01)) { map.put(sum01,map.get(sum01) + 1); }else{ map.put(sum01,1); } } } for (int num03 : nums3) { for (int num04 : nums4 ) { int needNum01 = 0 - (num03 + num04); if (map.containsKey(needNum01)) { res += map.get(needNum01); } } } return res; } }
|