您的位置:首页 > 编程语言 > Java开发

Leetcode-454. 4Sum II

2017-01-05 07:39 405 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

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.

Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

这个题目还算简单的,用一个Map保存前两个数组组合后可能的结果,然后后两个数组去看map中有没有相对应的负值即可。Your runtime beats 15.68% of java submissions.
public class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer,Integer> result2index = new HashMap<Integer,Integer>();
for(int i = 0; i < A.length; i ++)
for(int j = 0; j < B.length; j ++){
int result = A[i] + B[j];
if(result2index.containsKey(result)) result2index.put(result,result2index.get(result) + 1);
else result2index.put(result,1);
}
int count = 0;
for(int k = 0; k < C.length; k ++)
for(int l = 0; l < D.length; l ++){
int result = C[k] + D[l];
if(result2index.containsKey(-result)) count += result2index.get(-result);
}
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法