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 15 3Sum 找出数组里面3个数的和等于指定值。
- leetcode-java.T001_TwoSum 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字
- 寻找数组中和为指定数字的子数组,可以重复,Leetcode 39
- 一组数字,从1到n,从中减少了3个数,顺序打乱,放在n-3的数组里,找出丢失数字
- Two Sum(找出数组中两个和等于指定数字的元素)
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- 【LeetCode】- Single Number(从数组中找出只出现一次的数字)
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- 【leetcode】数组中找出只出现一次的数字(Single Number)
- leetcode-java.T015_3Sum---给定一个n个元素的数组,是否存在a,b,c三个元素,使用得a+b+c=0,找出所有符合这个条件的三元组
- 《剑指Offer》面试题:找出数组中有3个出现一次的数字
- 找出所有符合条件的记录的指定字段并分组统计个数,返回指定格式。
- [LeetCode] Find All Numbers Disappeared in an Array 找出数组中所有消失的数字
- 找出所有符合条件的记录的指定字段并分组统计个数,返回指定格式。
- 有一组数字,从1到n,从中减少了3个数,顺序也被打乱,放在一个n-3的数组里,请找出丢失的数字,最好能有程序,最好算法比较快
- LeetCode刷题记录8-根据条件反回指定字符串
- c++之数组篇1:对排序数组找出指定数字出现的次数
- 【leetcode】删除数组中指定要求的重复的数字
- 在数组中找出四个数字的和等于指定数字(4Sum)
- 一个整型数组里除了两个数字之外,其他的数字都出现了两次,请写程序找出这两个只出现一次的数字