鱼C论坛

 找回密码
 立即注册
查看: 1712|回复: 0

[学习笔记] leetcode 454. 4Sum II

[复制链接]
发表于 2019-10-1 13:28:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

  2. To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

  3. Example:

  4. Input:
  5. A = [ 1, 2]
  6. B = [-2,-1]
  7. C = [-1, 2]
  8. D = [ 0, 2]

  9. Output:
  10. 2

  11. Explanation:
  12. The two tuples are:
  13. 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  14. 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
复制代码

  1. class Solution {
  2.     public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
  3.         HashMap<Integer,Integer> map = new HashMap<>();
  4.         for(int i : A){
  5.             
  6.             for(int j: B){
  7.                 map.merge(i+j,1,(new BiFunction<Integer,Integer,Integer>(){public Integer apply(Integer i1, Integer i2){return i1+i2;}}));
  8.             }
  9.         }
  10.         int ret = 0;
  11.         for(int i : C){
  12.             
  13.             for(int j: D){
  14.                 ret += map.getOrDefault(-i-j,0);
  15.             }
  16.         }
  17.         return ret;
  18.         
  19.     }
  20. }
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-1 22:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表