Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
3sum.cpp 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-01-07 22:34 +08:00 . Rename 3-sum.cpp to 3sum.cpp
// Time: O(n^2)
// Space: O(1)
class Solution {
public:
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int>> threeSum(vector<int> &nums) {
vector<vector<int>> ans;
const int target = 0;
// Make nums in increasing order. Time: O(nlogn)
sort(nums.begin(), nums.end());
for (int i = 0; i < static_cast<int>(nums.size()) - 2; ++i) {
if (i == 0 || nums[i] != nums[i - 1]) { // Skip duplicated.
for (int j = i + 1, k = nums.size() - 1; j < k; ) { // Time: O(n) for each i.
if (j - 1 > i && nums[j] == nums[j - 1]) { // Skip duplicated.
++j;
} else if (k + 1 < nums.size() && nums[k] == nums[k + 1]) { // Skip duplicated.
--k;
} else {
const auto sum = nums[i] + nums[j] + nums[k];
if (sum > target) { // Should decrease sum.
--k;
} else if (sum < target) { // Should increase sum.
++j;
} else {
ans.push_back({nums[i], nums[j], nums[k]});
++j, --k;
}
}
}
}
}
return ans;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助