资料:
1. 排序:Sort函数
升序:默认。
降序:加入第三个参数,可以greater<type>(),也可以自己定义
本题中发现,sort居然也可以对vector<vector<int>>排序。
C++ Sort函数详解_zhangbw~的博客-CSDN博客
自己写的:
感觉我写的就是排列组合。
感觉时间复杂度很大,应该超过O(n^2)。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param num int整型vector
* @return int整型vector<vector<>>
*/
vector<vector<int> > threeSum(vector<int>& num) {
// write code here
vector<vector<int> > res;
for (int i = 0; i < num.size(); i++) {
for (int j = i + 1; j < num.size() - 1; j++) { // 粗心,是j = i + 1,不是j = i
if (find(num.begin() + j + 1, num.end(), -num[i] - num[j]) != num.end()) { //存在这样的[a,b,c]
vector<int> temp = {num[i], num[j], -num[i] - num[j]}; // 粗心,不是temp = {i, j, -i-j};
sort(temp.begin(), temp.end());
if (find(res.begin(), res.end(), temp) == res.end()) //之前没出现过这样的[a,b,c]
res.push_back(temp);
}
}
}
sort(res.begin(), res.end()); //题目中没说要排序啊!
return res;
}
};
模板的:
- 两个指针单向移动。保证答案的完整性。
- 三个值移动时都去重。保证答案的去重性。
- 处理边界的时候,需要思考很久。所以还是死记这种方法!!
- 由于两个指针在第二个循环里一起移动,所以时间复杂度确实是O(n^2).
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param num int整型vector
* @return int整型vector<vector<>>
*/
vector<vector<int> > threeSum(vector<int>& num) {
// write code here
vector<vector<int> > res;
int n = num.size();
if(n < 3)
return res;
sort(num.begin(), num.end()); // 粗心,忘记
for(int i = 0; i < n-2; i++){
// 去重
if( i != 0 && num[i] == num[i-1]){ //粗心,不是num[i] == num[i+1]
// i++; //粗心,不需要++的
continue;
}
int left = i + 1;
int right = n - 1;
while(left < right){
if(num[i]+num[left]+num[right]== 0){
res.push_back({num[i], num[left], num[right]}); //这种初始化!
while(left + 1 < right && num[left] == num[left+1]){ // 去重
left ++;
}
while(right - 1 > left && num[right] == num[right-1]){ // 去重
right --;
}
left ++; //粗心,忘记
right --; //粗心,忘记
}
else if (num[i]+num[left]+num[right] < 0)
left ++;
else
right --;
}
}
return res;
}
};