您的位置:首页 > 其它

LeetCode刷题记录7-从数组中找出指定条件的3个数字

2017-12-17 17:15 561 查看

题目

给定一个数组nums的n个整数,a,b,c在nums中,并且a + b + c = 0。在数组中找到所有唯一的三个数字,它们的总和为零。(并且每一组由3个数字组成并每一组不存在完全相同的情况)

如下:

For example, given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]


三层for循环

这种可能是能想到的最简单的方法了,遍历每一组数,然后计算结果,并去除重复(这也是本人想到的笨方法)。

我想要介绍的主要是第二种解法,具体如下:

跳过已扫描的数字

因为a+b+c=0,所以我们需要固定一个数字a,取反(-a),在剩余的数字中查找b+c和其相等的数字,并且遇到重复我们需要继续扫描下一个数字(该解法来自leedCode,链接会在文本最下方):

vector<vector<int> > threeSum(vector<int> &num) {
//[-1, 0, 1, 2, -1, -4]

vector<vector<int> > res;

std::sort(num.begin(), num.end());

for (int i = 0; i < num.size(); i++) {

int target = -num[i];
int front = i + 1;
int back = num.size() - 1;

while (front < back) {

int sum = num[front] + num[back];

// Finding answer which start from number num[i]
if (sum < target)
{
front++;
}
else if (sum > target)
{
back--;
}
else
{
vector<int> triplet(3, 0);
triplet[0] = num[i];
triplet[1] = num[front];
triplet[2] = num[back];
res.push_back(triplet);

// Processing duplicates of Number 2
// Rolling the front pointer to the next different number forwards
while (front < back && num[front] == triplet[1]) front++;

// Processing duplicates of Number 3
// Rolling the back pointer to the next different number backwards
while (front < back && num[back] == triplet[2]) back--;
}
}

// Processing duplicates of Number 1
while (i + 1 < num.size() && num[i + 1] == num[i])
i++;
}
return res;
}


原地址在这

https://leetcode.com/problems/3sum/discuss/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode
相关文章推荐