3Sum Closest
来源:互联网 发布:对冲平仓 知乎 编辑:程序博客网 时间:2024/06/04 18:20
Problem Description:
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).
Analyse:
这题和3sum的解法一样,可以用夹逼定理,不断缩小范围来定位和比较,重要的是不用去除重复。
Answer:
int threeSumClosest(vector<int>& nums, int target){ sort(nums.begin(),nums.end()); int minx = abs(target - nums[1]-nums[0]-nums[2]); int record = nums[0]+nums[1]+nums[2]; int gg = record; for(int i = 0; i<nums.size(); i++) { int k = i+1,j = nums.size()-1; while(k<j) { if(nums[i]+nums[j]+nums[k] == target)return target; else if(nums[i]+nums[j]+nums[k]<target) { record = nums[i]+nums[j]+nums[k]; if(target - record < minx) { minx = target - record; gg = record; } k++; } else { record = nums[i]+nums[j]+nums[k]; if(record - target<minx) { minx = record - target; gg = record; } j--; } } } return gg;}
阅读全文
0 0
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- LeetCode: 3 Sum Closest
- 3Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- leetcode002:3sum closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- 3Sum Closest
- [LeetCode] 3Sum Closest
- 用Java近似求pi,利用公式pi=4*(1-1/3+1/5-1/7+.....)
- js把字符串中的/全部替换成-
- Android 中 更新视图的函数ondraw() 和dispatchdraw()的区别
- C++ 多态
- 99乘法表
- 3Sum Closest
- 【云栖精选7月刊】抛开晦涩的算法、模型_让我们来谈谈互联网架构
- java.lang.OutOfMemoryError异常解决方法
- ZOJ1181 Word Amalgamation 字符串 排序查找
- 深入理解javascript原型和闭包(2)——函数和对象的关系
- MySQL优化的一些建议
- 解决The current branch is not configured for pull No value for key branch.master.merge found in config
- 在Spring3中使用注解(@Scheduled)创建计划任务
- SQL Server查看所有表大小,所占空间