3Sum Closest从数列中找到三个数之和最接近给定值
来源:互联网 发布:php开发游戏服务器 编辑:程序博客网 时间:2024/04/29 16:59
即求min{ target - a -b -c } a,b,c blog to Set S;
(一)最简单的做法当然是求出所有的不相同的三个数和,保存到set里,然后用target,target (+/-) i ,i [0....]
复杂度基本上可以算是O(n^3)。
int threeSumClosest(vector<int> &num, int target) { int n=num.size(); if(n<3) return 0; unordered_set<int> sum; for(int i=0 ; i<n; ++i) for(int j=i+1;j<n; ++j) for(int k=j+1; k<n;++k){ int key = num[i]+num[j]+num[k]; sum.insert(key); } int lap=0; while(true){ if(sum.find(target+lap)!=sum.end()) return target+lap; else if (sum.find(target-lap)!=sum.end()) return target-lap; lap++; }}
(二)有了简单解法,我们自然要优化。
(1)三重循环肯定是可以干掉的,即先把两数之和和它们对应的下标存到map里。
(2)然后再用数组的数去map里映射,最初是a[i] +0 , 然后是a[i] +1 ,依次增加,总会找到的。
(3)这样基本上算是O(N^2)了。
int threeSumClosest(vector<int> &num, int target) { int n=num.size(); if(n<3) return 0; unordered_map<int,pair<int,int>> num0; for(int i=0 ; i<n; ++i) for(int j=i+1;j<n; ++j){ int key = target-num[i]-num[j]; num0.insert(make_pair(key,make_pair(i,j))); } int lap=0; while(true){ for(int i=0 ; i< num.size();++i){ if( num0.find(num[i]+lap)!=num0.end() && i!=num0[num[i]+lap].first &&i!=num0[num[i]+lap].second ) return target-lap; else if(num0.find(num[i]-lap)!=num0.end() && i!=num0[num[i]-lap].first &&i!=num0[num[i]-lap].second ) return target+lap; } lap++; }}
0 0
- 3Sum Closest从数列中找到三个数之和最接近给定值
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 16. 3Sum Closest(找出和最接近给定值的三个数)
- 3Sum Closest 三个数的和最接近某个值
- LeetCode | 3Sum Closest(找到三个数使其和与target最接近)
- 找出序列中求和最接近于target的三个数 3Sum Closest
- LeetCodet题解--16. 3Sum Closest(离给定值最近的三数之和)
- Leetcode #16 3Sum Closest 找3数之和最接近 解题小节
- LeetCode 3Sum Closest 最接近目标数的三个数和
- 3Sum Closest 三数最接近
- leetcode-java.T016_threeSumClosest---给定包含n个整数数组S,找到S中的三个整数,从而使之和最接近给定的数,返回三个整数的总和.
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- Leetcode刷题记——16. 3Sum Closest(最接近的三个数的和)
- leetCode 16.3Sum Closest (离给定值最近的三数之和) 解题思路和方法
- 3Sum 三个数之和
- 【LeetCode-面试算法经典-Java实现】【016-3 Sum Closest(最接近的三个数的和)】
- 59.3Sum Closest-最接近的三数之和(中等题)
- 最接近3数之和
- linux 常用命令
- 后缀树简介-Pattern Searching | Set 8 (Suffix Tree Introduction)
- requirejs的优点及缺点
- vim c编程初步配置
- nyoj 410 how many ones?
- 3Sum Closest从数列中找到三个数之和最接近给定值
- vim 查看函数列表
- UITableView出现卡顿如何处理
- 博客搬家
- 第十五周上机项目3--(2)指针戏谑
- poj 1882 背包(从1开始的连续邮票数量)
- nyoj860又见01背包
- JNI常用函数
- SSH系列(一)struts入门