由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 我这个 4sum的解法是 o^3还是o^2? , xiexie
相关主题
我这个 3Sum 怎么过不了leetcode的测试阿LC 4-sum相当麻烦啊
Leetcode 4SUM 总是超时问个array in place operation的题目
lc 上面4 sum的时间复杂度要求多少?问一道题(5)
Maximal Rectangle O(mn) 解法 非 histogram一道大公司诡异的complete binary tree max sum of 2 nodes 题
NB的解法:Gray code!g公司面试问Longest increasing subsequence,意义在哪里?
求助:3sum总是运行不过关于最长递增子序列的问题。
leetcode 4sum N^3解法有时Time Limit Exceeded有时又能通过请问两道题
求个4sum的算法问一道G家经典老题
相关话题的讨论汇总
话题: num话题: int话题: vector话题: 4sum话题: else
进入JobHunting版参与讨论
1 (共1页)
t**r
发帖数: 3428
1
class Solution {
public:
vector > fourSum(vector &num, int target) {
int n = num.size();
vector > ret;
sort(num.begin(), num.end());
for (int i = 0; i < n; ++i) {
if (i != 0 && num[i] == num[i - 1]) continue;
for (int j = n - 1; j > i; --j) {
if (j != n - 1 && num[j] == num[j + 1]) continue;
int L = i + 1, R = j - 1;
while (L < R) {
int sum = num[i] + num[L] + num[R] + num[j];
if (L != i + 1 && num[L] == num[L - 1]) {
L++;
} else if (R != j - 1 && num[R] == num[R + 1]) {
R--;
} else if (sum > target) {
R--;
} else if (sum < target) {
L++;
} else {
ret.resize(ret.size() + 1);
ret.back().push_back(num[i]);
ret.back().push_back(num[L]);
ret.back().push_back(num[R]);
ret.back().push_back(num[j]);
L++;
R--;
}
}
}
}
return ret;
}
};
我这个 4sum的解法是 o^3还是o^2? , xiexie
s******6
发帖数: 4
2
4sum 问题复杂度是O^3的
i******s
发帖数: 301
3
枚举所有pair, 一共有n*(n-1) / 2个,然后转化为求2sum。重点是去重,可以在pair
里面记录在原来数组的index。所以最好是O(n^2)吧。你的解法应该是O(n^3)
i******s
发帖数: 301
g*********e
发帖数: 14401
5
你这是n3
z***m
发帖数: 1602
6
如果不用hash来缓存2个数的话,用排序的方法,应该是O(max(nlogn, n^(k-1))), 4-
sum就是n^3了
1 (共1页)
进入JobHunting版参与讨论
相关主题
问一道G家经典老题NB的解法:Gray code!
求 Maximum Subarray divide and conquer 解法求助:3sum总是运行不过
Finding all paths sum up to a given value in 150不对吧?leetcode 4sum N^3解法有时Time Limit Exceeded有时又能通过
divide array into two, sum of difference is min in O(N)求个4sum的算法
我这个 3Sum 怎么过不了leetcode的测试阿LC 4-sum相当麻烦啊
Leetcode 4SUM 总是超时问个array in place operation的题目
lc 上面4 sum的时间复杂度要求多少?问一道题(5)
Maximal Rectangle O(mn) 解法 非 histogram一道大公司诡异的complete binary tree max sum of 2 nodes 题
相关话题的讨论汇总
话题: num话题: int话题: vector话题: 4sum话题: else