首页 > 其他 > 详细

Jan 14 - 3 Sum Closest; Array; Two Pointer;

时间:2016-01-15 12:35:04      阅读:109      评论:0      收藏:0      [点我收藏+]

最原始的方法:

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        if(len < 2) return 0;
        int i = 0;
        int sum = nums[0]+nums[1]+nums[2];
        int minDiff = sum - target;
        minDiff = minDiff < 0? (-1)*minDiff: minDiff;
        if(minDiff == 0) return sum;
        while(i < len - 2){
            for(int j = i + 1; j < len-1; j++){
                for(int k = j + 1; k < len; k++){
                    int temp = nums[i] + nums[j] + nums[k];
                    int diff = temp - target;
                    diff = diff < 0? (-1)*diff : diff;
                    if(diff == 0) return temp;
                    if(diff < minDiff){
                        minDiff = diff;
                        sum = temp;
                    }
                }
            }
            i++;
        }
        return sum;
    }
}

  思维盲区,对原数组进行操作,其实只要题目没要求保留数组不变,我们可以先对数组排序(or other operation),这样数组不再是随机排列,查找起来就方便很多。Runtime 变为O(n^2);

代码:

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int i = 0;
        int sum = nums[0]+nums[1]+nums[2];
        int minDiff = sum - target;
        minDiff = minDiff < 0? (-1)*minDiff: minDiff;
        if(minDiff == 0) return sum;
        while(i < len - 2){
            int low = i + 1;
            int high = len - 1;
            while(low < high){
                int temp = nums[i] + nums[low] + nums[high];
                if(temp == target) return target;
                while(low < high && temp < target){
                    int diff = temp - target;
                    diff = diff < 0? (-1)*diff : diff;
                    if(diff < minDiff){
                        minDiff = diff;
                        sum = temp;
                    }
                    low++;
                    temp = nums[i] + nums[low] + nums[high];
                }
                while(low < high && temp > target){
                    int diff = temp - target;
                    diff = diff < 0? (-1)*diff : diff;
                    if(diff < minDiff){
                        minDiff = diff;
                        sum = temp;
                    }
                    high--;
                    temp = nums[i] + nums[low] + nums[high];
                }
                
            }
            i++;
        }
        return sum;
    }
}

  

Jan 14 - 3 Sum Closest; Array; Two Pointer;

原文:http://www.cnblogs.com/5683yue/p/5132813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!