由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 以前能过的leetcode 3sum, 现在fail了, 求助(时间超出了)
相关主题
[a9面经] print x,y,z刷题弱人来问个two sum的题目
3sum on LeetCode OJ问一个3 sum的问题
问求array中3个数和最接近k的解法一道google 经典题
LC的3sum谁有简洁代码?CS algorithm question
leetcode上的3sum一FG家常见题
请问如何去除结果里面的重复问个G的题目
问个题sleetcode中的online judge都报runtime error, 用本地编译器执行一些例子都ok
弱问:不好意思,这个CODE问题在哪里?A家电面
相关话题的讨论汇总
话题: nums话题: int话题: vector话题: tail话题: head
进入JobHunting版参与讨论
1 (共1页)
t*****t
发帖数: 285
1
Given an array S of n integers, are there elements a, b, c in S such that a
+ b + c = 0? Find all unique triplets in the array which gives the sum of
zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b
≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
class Solution {
private:
int increment(vector& nums, int l, int r){
while(l return l;
}

int decrement(vector& nums, int l, int r){
while(r>l && nums[r]==nums[--r]){}
return r;
}

public:
vector> threeSum(vector& nums) {
vector> res;
if(nums.size()<3) return res;

sort(nums.begin(), nums.end());
for(int i=0; i int l = i+1;
int r = nums.size()-1;
while(l if(nums[i]+nums[l]+nums[r] == 0){
vector tmp {nums[i], nums[l], nums[r]};
res.push_back(tmp);
l = this->increment(nums,l,r);
r = this->decrement(nums,l,r);
}
else if(nums[i]+nums[l]+nums[r] < 0){
l = this->increment(nums,l,r);
}
else{
r = this->decrement(nums,l,r);
}
}
}
return res;
}
};
u**l
发帖数: 35
2
class Solution {
public:
vector> threeSum(vector& nums) {
vector> ret;
if (nums.size() < 3) {
return ret;
}
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; ++i) {
if (i > 0 && nums.at(i) == nums.at(i - 1)) {
continue;
}
twoSum(ret, i + 1, nums, 0 - nums.at(i));
}
return ret;
}
private:
void twoSum(vector>& res, int index, vector& sortedNums
, int target) {
int head = index;
int tail = sortedNums.size() - 1;
while (head < tail) {
int tmp = sortedNums.at(head) + sortedNums.at(tail);
if (tmp < target) {
++head;
}
else if (tmp > target) {
--tail;
}
else {
vector v;
v.push_back(sortedNums.at(index - 1));
v.push_back(sortedNums.at(head));
v.push_back(sortedNums.at(tail));
res.push_back(v);
int k = head + 1;
while (k < tail && sortedNums.at(k) == sortedNums.at(head)) {
++k;
}
head = k;
k = tail - 1;
while (k > head && sortedNums.at(k) == sortedNums.at(tail)) {
--k;
}
tail = k;
}
}
}
};
t*****t
发帖数: 285
3
感谢啊,这年头,越来越难啊
1 (共1页)
进入JobHunting版参与讨论
相关主题
A家电面leetcode上的3sum
问个fb onsite题目请问如何去除结果里面的重复
amazon版上面试问题请教问个题
facebook telephone interview from careercup弱问:不好意思,这个CODE问题在哪里?
[a9面经] print x,y,z刷题弱人来问个two sum的题目
3sum on LeetCode OJ问一个3 sum的问题
问求array中3个数和最接近k的解法一道google 经典题
LC的3sum谁有简洁代码?CS algorithm question
相关话题的讨论汇总
话题: nums话题: int话题: vector话题: tail话题: head