• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: 4Sum II

Time Complexity: O(n^2)

 1 public class Solution {
 2     public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
 3         int len = A.length;
 4         int ans = 0;
 5         Map<Integer, Integer> countAB = new HashMap<Integer, Integer>();
 6         Map<Integer, Integer> countCD = new HashMap<Integer, Integer>();
 7         for (int i = 0; i < len; i++) {
 8             for (int j = 0; j < len; j++) {
 9                 Integer g = new Integer(A[i] + B[j]);
10                 if (countAB.containsKey(g)) {
11                     int v = countAB.get(g);
12                     countAB.put(g, ++v);
13                 }
14                 else countAB.put(g, 1);
15                 g = new Integer(C[i] + D[j]);
16                 if (countCD.containsKey(g)) {
17                     int v = countCD.get(g);
18                     countCD.put(g,  ++v);
19                 }
20                 else countCD.put(g, 1);
21             }
22         }
23         for (Integer key : countAB.keySet()) {
24             if (countCD.containsKey(-key)) {
25                 ans += countAB.get(key) * countCD.get(-key);
26             }
27         }
28         return ans;
29     }
30 }

 

posted @ 2016-11-17 13:49  ying_vincent  阅读(124)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3