3Sum Closest 3个数字的和等于或者最接近与目标数
2015-04-01 11:22
218 查看
3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers.You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution { public: int threeSumClosest(vector<int> &num, int target) { int len,i,left,right,min,ans,sum; sort(num.begin(),num.end()); len=num.size(); min=9999999; for(i=0;i<len-1;i++) { left=i+1; right=len-1; while(left<right) { sum=num[i]+num[left]+num[right]; if(abs(target-sum)<min) { min=abs(target-sum); ans=sum; } if(sum<target) { left++; } else if(sum>target){ right--; } else{ return sum; } } } return ans; } };
相关文章推荐
- /*算法从9个数中取出3个3位数其中两个3位数相加等于另一个3位数其中每位数字不能重复,c语言怎么实现*/
- 二叉搜索树查找与目标数字最接近的节点。
- 神秘的三位数 有这样一个3位数,组成它的3个数字阶乘之和正好等于它本身。即:abc = a! + b! + c!
- 数组里找到和最接近于0的两个值?或者和等于0的两个值
- leetcode-java.T001_TwoSum 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字
- 从一个数组中查找和目标数最接近的或者相等的数
- hdu 3434 给你含有n个数的序列,每次你可以选一个子序列将上面所有的数字加1或者减1,目标是把所有数字变成相同的,问最少步数,和那个相同的数字有多少种可能
- 二叉搜索树中查找与目标数字最接近的节点
- 神秘的三位数 有这样一个3位数,组成它的3个数字阶乘之和正好等于它本身。即:abc = a! + b! + c!
- twoSum 必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。
- 查找和目标数最接近的或者相等的数
- 给定目标值,从数组中挑选出两个数字之和等于目标
- wiresharkIP过滤:包括来源IP或者目标IP等于某个IP比如
- 每日一道算法题——3个数字相加等于0
- LeetCode 3Sum Closest 最接近目标数的三个数和
- 文本框中的值只能为数字或者是小数
- Android限定EditText的输入类型为数字或者英文(包括大小写)
- Linux系统平均负载3个数字的含义
- 给定候选号码(C)和目标号码(T)的集合,找出C中候选号码总和为T的所有唯一组合 C中的每个数字只能在组合中使用一次。
- 管理的最高目标:1加1等于1 推荐