ITeye博客

3Sum Closest

plan454 · 2015-03-05 22:25 · leetcode刷题 · 非技术 · Markdown

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的思路一样

 public int threeSumClosest(int[] num, int target) {
        int result = 0;
        int temp = Integer.MAX_VALUE;
        if(num == null || num.length<3){
        	return 0;
        }
        Arrays.sort(num);
        for(int i = 0 ;i<num.length-1;i++){
        	int tar = target - num[i];
        	int end = num.length-1;
        	int begin = i+1;
        	while(end > begin){
        		if(tar> num[end]+num[begin]){
        			temp = Math.abs(temp)<Math.abs(tar- num[end] - num[begin])?temp:tar- num[end] - num[begin];
        			begin++;
        			while(begin<num.length&&num[begin] == num[begin-1]){
            			begin++;
            		}
        		}else if(tar<num[end]+num[begin]){
        		
        			
        			temp = Math.abs(temp)<Math.abs(tar- num[end] - num[begin])?temp:tar- num[end] - num[begin];
        			end--;
        			while(end>-1&&num[end] == num[end+1]){
            			end--;
            		}
        		}else {
        			return target;
        		}
        		
        		
        		
        	}
        	
        	
        }
        result = target - temp;
        return result;
    }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。