由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - LeetCode 的 4 sum 问题 如何用hash table做呢?
相关主题
4sum o(n^2)超时A家新鲜面经--都是经典题
求个4sum的算法请教LeetCode的3Sum
leetcode上遇到的问题关于Hash_map
leetcode 4sum N^3解法有时Time Limit Exceeded有时又能通过leetcode 上的 two sum
问个Java的HashSet.contains的问题LC 4-sum相当麻烦啊
Linked电面分享,挺好的题 应该已挂求点评:电话面试(今天第二天没有消息回复,感觉可能挂了)
subsetSecond round phone interview with eBay
3sum on LeetCode OJa problem from leetcode: high efficiency algorithm for combinations problem
相关话题的讨论汇总
话题: integer话题: arraylist话题: num话题: int话题: sum
进入JobHunting版参与讨论
1 (共1页)
H*****l
发帖数: 1257
1
我用类似3 sum的方法,是O(n^3)的复杂度,但是过不了large judge,超时;
看到帖子说可以用hash table做到O(n^2)的复杂度,能不能具体说下算法?
题目如下:
Given an array S of n integers, are there elements a, b, c, and d in S such
that a + b + c + d = target? Find all unique quadruplets in the array which
gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ?
b ? c ? d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
f****n
发帖数: 1
2
O(n^2)两两配对求和,对这些和再做two sum吧
H*****l
发帖数: 1257
3
怎么在O(n^2)时间内既求和又能对结果排序,还可以从求和后的idx恢复原来两个数的
idx呢……?

【在 f****n 的大作中提到】
: O(n^2)两两配对求和,对这些和再做two sum吧
d*******y
发帖数: 27
4
基本上2,3,4-sum都是一个思路吧,用hashmao做一个的索引。我之前做
的时候都是优化一个指数级别就可以过large set了。
import java.util.*;
public class Solution {
public ArrayList> fourSum(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
HashSet> result = new HashSet>
();
HashMap map = new HashMap();
ArrayList> rtn = new ArrayList
>();
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
map.put(num[i], i);
}
for (int i = 0; i < num.length - 3; i++) {
for (int j = i + 1; j < num.length - 2; j++) {
for (int k = j + 1; k < num.length - 1; k++) {
int diff = target - num[i] - num[j] - num[k];
if (map.containsKey(diff)) {
int l = map.get(diff);
if (l != i && l != j && l != k && l > k) {
ArrayList current = new ArrayList<
Integer>(4);
current.add(num[i]);
current.add(num[j]);
current.add(num[k]);
current.add(num[l]);
result.add(current);
}
}
}
}
}
Iterator> it = result.iterator();
while (it.hasNext()) {
rtn.add(it.next());
}
return rtn;
}
}
1 (共1页)
进入JobHunting版参与讨论
相关主题
a problem from leetcode: high efficiency algorithm for combinations problem问个Java的HashSet.contains的问题
一道电面题,分享下, 这个题应该用哪几个data structure?Linked电面分享,挺好的题 应该已挂
leetcode 129subset
word ladder ii 谁给个大oj不超时的?3sum on LeetCode OJ
4sum o(n^2)超时A家新鲜面经--都是经典题
求个4sum的算法请教LeetCode的3Sum
leetcode上遇到的问题关于Hash_map
leetcode 4sum N^3解法有时Time Limit Exceeded有时又能通过leetcode 上的 two sum
相关话题的讨论汇总
话题: integer话题: arraylist话题: num话题: int话题: sum