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
are such that
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:
这个题目还算简单的,用一个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;
}
}
博客链接: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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- Debian 7.x 安装Oracle JAVA
- springmvc实现url路由功能
- spring boot 配置 druid/** * 配置druid * Created by adam on 4/11/16. */ @Configuration public class D