LeetCode刷题记录7-从数组中找出指定条件的3个数字
来源:互联网 发布:如何升级linux 编译器 编辑:程序博客网 时间:2024/05/17 21:01
题目
给定一个数组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/
阅读全文
0 0
- LeetCode刷题记录7-从数组中找出指定条件的3个数字
- LeetCode刷题记录3-求数字是否为回文
- leetcode刷题记录4--依然数组
- leetcode刷题记录5--依旧数组
- leetcode刷题记录
- leetcode刷题记录
- leetcode刷题记录
- leetcode 刷题记录
- leetcode刷题记录
- Leetcode刷题记录
- Leetcode刷题记录
- leetcode 刷题记录
- LeetCode刷题记录
- 【LeetCode刷题记录】
- LeetCode刷题记录3-Majority Element
- 面试题:从1001个整数元素的数组中找出重复的数字
- 【LeetCode】- Single Number(从数组中找出只出现一次的数字)
- leetCode 刷题记录 Candy
- 剑指offer 编程题(10):二进制中1和0的个数
- JSON的初步理解
- vue的项目搭建
- caffe
- mobx基本使用
- LeetCode刷题记录7-从数组中找出指定条件的3个数字
- zookeeper报错Error contacting service. It is probably not running.
- 链表的从尾到头打印(四种方法)
- linux作业
- 2017.12.17Day15
- Python(3) python小知识--reduce(), range(), lambda
- virtual dj studio中文版 | Virtual DJ Studio(专业级DJ混音软件)官方注册版V7.8.5下载 | virtual dj studio 7混音器
- adb命令
- 如何在js中操作样式