题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
#include <vector>
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;
// 3重循环
for (int i = 0; i < num.size(); i++) {
for (int j = i + 1; j < num.size(); j++) {
for (int k = j + 1; k < num.size(); k++) {
vector<int> temp;
if (num[i] + num[j] + num[k] == 0) {
// 排序
// temp.push_back(num[i]);
// temp.push_back(num[j]);
// temp.push_back(num[k]);
int a = num[i];
int b = num[j];
int c = num[k];
int t = 0;
if (a > b) { /*如果a大于b,借助中间变量t实现a与b值的互换*/
t = a;
a = b;
b = t;
}
if (a > c) { /*如果a大于c,借助中间变景t实现a与c值的互换*/
t = a;
a = c;
c = t;
}
if (b > c) { /*如果b大于c,借助中间变量t实现b与c值的互换*/
t = b;
b = c;
c = t;
}
temp.push_back(a);
temp.push_back(b);
temp.push_back(c);
res.push_back(temp);
}
}
}
}
// 去重
set<vector<int>>s(res.begin(), res.end());
res.assign(s.begin(), s.end());
return res;
}
};
滴滴公司福利 1829人发布