標簽(空格分隔): C++ 算法 LetCode 數組
每日算法——letcode系列
問題 Longest Common Prefix
Difficulty: Medium
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.
<pre>
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
</pre>
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
}
};
翻譯
三數和
難度系數:中等
給定一個有n個整數的數組S, 判斷是否存在a, b, c三個元素滿足a + b + c = 0? 找到數組中所有滿足和為零的三個數(數組中不能有重復的三個數) 。
思路
如果隨機找$C_n^3$種方案。假定滿足條件的三個數為a,b,c,這三個數索引分別為i, j, k。先排序,從數組的頭確定一個數a,b的索引比a大1,c為數組的尾,有三種情況
- a + b + c = target 則i++ k-- 并把這三個數記錄下來
- a + b + c < target 則j++
- a + b + c < target 則k--
終止條件b < c。
相當于確定兩個,動一個,這樣比較好確定方案
代碼
class Solution {
public:
vector<vector<int>> threeSum(vector<int> &nums) {
vector<vector<int> > result;
// 排序
sort(nums.begin(), nums.end());
int n = static_cast<int>(nums.size());
for (int i = 0; i < n - 2; ++i) {
// 去重復
// 下面注釋掉的去重復方案是錯誤的, 會把0,0,0也去掉
// while (i < n -2 && nums[i] == nums[i+1]) {
// i++;
// }
if (i>0 && nums[i-1] == nums[i]){
continue;
}
int j = i + 1;
int k = n - 1;
while (j < k) {
if (nums[i] + nums[j] + nums[k] < 0){
// 去重復
while (j < k && nums[j] == nums[j+1]) {
j++;
}
j++;
}
else if (nums[i] + nums[j] + nums[k] > 0){
// 去重復
while (k > j && nums[k] == nums[k-1]) {
k--;
}
k--;
}
else{
result.push_back({nums[i], nums[j], nums[k]});
// 去重復
while (j < k && nums[j] == nums[j+1]) {
j++;
}
while (k > j && nums[k] == nums[k-1]) {
k--;
}
j++;
k--;
}
}
}
return result;
}
};