题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
一、知识点
数组 滑动窗口
二、解题思路
最外层遍历数据,a+b+c=0转换为b+c=-a。
左边界left设为i+1,右边界right设为len-1。
不断缩小窗口范围寻找满足条件的b和c,注意跳过相邻的重复数字。
三、C++解法
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param num int整型vector
* @return int整型vector<vector<>>
*/
vector<vector<int> > threeSum(vector<int>& num) {
sort(num.begin(), num.end());
int len = num.size();
vector<vector<int>> ret;
for (int i = 0; i < len; i ++) {
if (i > 0 && num[i] == num[i-1]) {
continue;
}
int target = -num[i];
int left = i + 1, right = len - 1;
while (left < right) {
int val = num[left] + num[right];
if (val == target) {
ret.push_back(vector<int>{num[i], num[left], num[right]});
while (left < right && num[left] == num[left+1]) {
left ++;
}
while (left < right && num[right] == num[right-1]) {
right --;
}
left ++;
right --;
} else if (val < target) {
left ++;
} else {
right --;
}
}
}
return ret;
}
};
#在找工作求抱抱#面试必刷Top101-题解 文章被收录于专栏
手把手带你刷题