3Sum Closest
来源:互联网 发布:计算机编程跟黑客 编辑:程序博客网 时间:2024/06/15 21:35
题目: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).
思路:
与之前的求解方法一样,只不过本题变成求和最接近的和,用绝对值即可。
程序里面的一个技巧就是,遇到重复数字直接跳过,这是因为,第一次的时候,就已经考虑后面的了,比如说1,1,1,2
第一个选择1的时候,后面就已经有left等于后面的1,所以同样的道理,最后也是要从后往前找不同的第一个点,至于找到了,相同的pass。
程序的另外一个技巧就是,遇到等于目标数字的,直接赋值,而有不同的,再去进行比较,这里指绝对值。至于后面大于小于的情况,作同样处理。
代码:
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { int length=nums.size(); sort(nums.begin(),nums.end()); int left=0,right=length-1; int res=INT_MAX,result=target; for(int i=0;i<length-2;i++){ if(i>0 && nums[i]==nums[i-1]){ continue; } int a=nums[i]; int left=i+1,right=length-1; while(left<right){ int b=nums[left],c=nums[right]; int sum=a+b+c; if(sum==target){ return target; }else{ if(abs(target-sum)<=res){ res=abs(target-sum); result=sum; } if(sum>target){ right--; while(nums[right]==nums[right+1]){ right--; } } if(sum<target){ left++; while(nums[left]==nums[left-1]){ left++; } } } } } return result; }};
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
- Leetcode: Populating Next Right Pointers in Each Node II
- Search Insert Position
- C++中对sprintf()函数的说明
- CocoaPods pod install/pod update更新慢的问题
- Android progressbar 进度条的使用
- 3Sum Closest
- 杭电ACM1509
- Gradle Plugin Samples (一)
- Linux下实现编写汇编程序
- Spiral Matrix
- Ubuntu下安装GCC编译器
- [LeetCode] Palindrome Linked List
- linux shell用法(3)-- shell 格式总结
- Gradle Plugin Samples 之 Gradle Hello World (二)