三数之和 (写一篇正经的博客)
来源:互联网 发布:男生健身知乎 编辑:程序博客网 时间:2024/05/19 19:16
给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
思路简单 枚举前两个 然后三分 。
主要是防重 操作 比如 一个数组 有 1 2 5 可以选
5 2 1 1 5 2 等都是重复的
所以每次枚举 前两个 然后 二分 最后一个到最后一个元素 ;
这样也会有重复 用 set 容器去重 ,加入set容器的数组要排序 不然去重不了。
然后 set输出时 得倒过来输出 ,因为set输出时 第一个元素绝对值大在后面、、
class Solution {public: /** * @param numbers : Give an array numbers of n integer * @return : Find all unique triplets in the array which gives the sum of zero. */ int sanfen(int left, int right,vector< int> nums,int x) { if(left==right) return left; int mid1=(left+right)/2; if(nums[mid1]>=x) return sanfen(left,mid1,nums,x); else return sanfen(mid1+1,right,nums,x); } int panduan(int min,int max1,vector<int> nums) { int sum1=nums.size();//cout<<sum1<<endl; int home=0-nums[min]-nums[max1]; int x1=-1;int x2=-1;int x3=-1; //if(min-1>=0)x1=sanfen(0,min-1,nums,home); // if(max1-1>=min+1) x2=sanfen(min+1,max1-1,nums,home);//cout<<max1; if(max1+1<=sum1-1) x3=sanfen(max1+1,sum1-1,nums,home);// cout<<x3<<endl; // if(nums[x1]==home) //return x1; // if(nums[x2]==home) // return x2; if(nums[x3]==home) return x3; return -1; } vector<vector<int> > threeSum(vector<int> &nums) { set<vector<int>> s; bool xa=1; vector<vector<int> > po; vector<int> por; int x= nums.size(); sort(nums.begin(),nums.end()); for(int i=0;i<x;i++) for(int j=i+1;j<x;j++) { xa=1; int x=panduan(i,j,nums); if(x!=-1) { por.push_back(nums[i]); por.push_back(nums[j]); por.push_back(nums[x]); //po.push_back(por); sort(por.begin(),por.end()); s.insert(por); por.clear(); } } set<vector<int>>::reverse_iterator rit; for(rit=s.rbegin();rit!=s.rend();rit++) po.push_back(*rit); reverse(po.begin(),po.end()); return po;// write your code here }};
阅读全文
0 0
- 三数之和 (写一篇正经的博客)
- 如何写一个正经的Android音乐播放器 三
- 【lintcode】两数之和、三数之和、最接近的三数之和、四数之和小结
- 我是正经的第一篇!
- 最接近的三数之和
- 最接近的三数之和
- 复赛后第一次正经写博客
- 咸鱼用9.99$体验VR(一篇越写越不正经的偏题博客)
- 写的第一篇博客
- 这是一篇正经的博文
- 第一篇博客-写博客的动机
- 三数之和为0的组合
- LintCode:最接近的三数之和
- LintCode 52-最接近的三数之和
- LintCode 59 最接近的三数之和
- 最接近的三数之和 _LintCode
- LintCode 三数之和
- 三数之和
- tcp的关闭过程
- 操作系统刷题(十四)
- 使用gulp压缩css文件
- eureka.instance.appname 与 spring.application.name 的区别
- 深究AngularJS——自定义服务详解(factory、service、provider)
- 三数之和 (写一篇正经的博客)
- 堆栈的简单实现之一:基本操作(C语言实现)
- 代码埋点
- FFmpeg跳转函数调用
- 荣耀砸场子 为新品造势之余还不忘暗讽小米
- 子数组之和
- git解决冲突
- 【算法题】数列还原
- java的MD5加密的几种方法