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).

思想:将3Sum简化为2Sum,采用从前和从后同时查找的方式进行搜索;
注意事项:优化,先排序后,对相邻相同数字的优化;其次对向前和向后相同数字的优化。
JAVA 代码:
  1. public int threeSumClosest(int[] num, int target) {
  2. int len = num.length;
  3. if(len<3) return 0;
  4. // float min = (float)Integer.MAX_VALUE;
  5. int min = num[0] + num[1] + num[2];  //注意min的选取
  6. Arrays.sort(num);
  7. for(int i=0;i<=len-3;i++) {
  8. if(i>0 && num[i] == num[i-1]) continue;
  9. int start = i+1;
  10. int end = len-1;
  11. while(start<end){
  12. if(num[start] + num[end] + num[i] == target) {
  13. return target;
  14. } else {
  15. if(Math.abs(num[start] + num[end] + num[i] - target) < Math.abs(min-target)) {
  16. min = num[start] + num[end] + num[i];
  17. }
  18. if(num[start] + num[end] + num[i] > target) {
  19. end--;
  20. while(end>=0 && num[end]==num[end+1]) end--;
  21. } else {
  22. start++;
  23. while(start<len&&num[start]==num[start-1]) start++;
  24. }
  25. }
  26. }
  27. }
  28. return min;
  29. }

未优化的C++代码:

  1. int threeSumClosest(vector<int> &num, int target) {
  2. if(num.size()<3) return 0;
  3. sort(num.begin(),num.end());
  4. int sz = num.size();
  5. int minSum = num[0]+num[1]+num[2];
  6. for(int i=0;i<sz-2;i++) {
  7. int tmp=num[i];
  8. int start = i+1;
  9. int end=sz-1;
  10. while(start<end) {
  11. int sum=tmp+num[start]+num[end];
  12. if(sum==target) return sum;
  13. if(abs(target-sum)<abs(minSum-target)) minSum= sum;
  14. if(sum>target) {
  15. end--;
  16. } else {
  17. start++;
  18. }
  19. }
  20. }
  21. return minSum;
  22. }
posted @ 2014-07-10 22:46  purejade  阅读(86)  评论(0)    收藏  举报