排序+对撞指针(15. 3Sum )
来源:互联网 发布:iphone导出照片软件 编辑:程序博客网 时间:2024/05/21 19:20
以leetcode题目为例:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[ [-1, 0, 1], [-1, -1, 2]]
#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace std;vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > res; std::sort(num.begin(), num.end()); // 双指针对撞 for (int i = 0; i < num.size(); i++) { int target = -num[i]; // 在[i+1..n-1]中用双指针对撞法,找两个数的值为target // 因为sort后,num[i]最小,因此取负号最大,由此可以确定在上述区间查找 int front = i + 1; int back = num.size() - 1; // 对撞指针终止于指针对撞 while (front < back) { int sum = num[front] + num[back]; // sum小的话就 front往后移 if (sum < target) front++; // sum小的话就 back往前移 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 while (front < back && num[front] == triplet[1]) front++; // Processing duplicates of Number 3 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;}
阅读全文
0 0
- 排序+对撞指针(15. 3Sum )
- LeectCode 16. 3Sum Closest *** 对撞指针
- LeetCode 15.3Sum 18.4Sum 对撞指针 ****
- leetcode 1. Two Sum排序+双指针
- 使用指针对字符串排序
- 利用指针对字符串排序
- 对3个数排序(学习数组和指针参数传递)
- 使用快速排序算法对字符串数组进行排序(复习指向指针的指针以及指针数组的使用)
- 两个指针-3sum, 3sum closes
- 16. 3Sum Closest 又是一道先排序再双指针问题
- 3Sum Closest-双指针
- 【Leetcode】3Sum - 【两个指针】
- 用指向指针的指针来对数组排序(字符串)
- Two Sum(初谈双指针)
- 【指针】【引用作形参】对三个变量排序
- 利用指针对两个数字进行排序
- 用指针对数组进行排序
- 用指针数组对字符串进行排序
- Oracle 分页
- 网络编程(IP、端口、协议)
- python 线程池的创建
- BZOJ 3160: 万径人踪灭 FFT+快速幂+manacher
- 使用Spring Cloud搭建服务注册中心
- 排序+对撞指针(15. 3Sum )
- Cookie/Session机制详解
- Python——PyCharm常用快捷键
- 下沉传递和冒泡响应的过程
- codility Peaks
- javascript常用的55个经典技巧
- 请阐述双亲委派机制...
- Rubost PCA 优化
- 2014 Multi-University Training Contest 1 D(hdu 4864 经典贪心)