F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[Leetcode] 3Sum Closest

使用2sum降低复杂度为O(N^2)

 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         Arrays.sort(nums);
 4         int closest =Integer.MAX_VALUE;
 5         boolean first = true;//if the first time, then there is no need to compare the tmpsum with the closest
 6         for(int i=0;i<nums.length-2;i++){
 7             int num = nums[i];
 8             int left = i+1;
 9             int right = nums.length-1;
10             
11             while(left<right){
12                 int tmpsum = num + nums[left] + nums[right];
13                 if(first){
14                     closest = tmpsum;
15                     first =false;
16                 }else{
17                     if(Math.abs(tmpsum-target)<Math.abs(closest - target)){
18                         closest = tmpsum;
19                     }
20                 }
21                 //move the left or the right pointer according to whether the tmpsum is larger than the target
22                 if(tmpsum<target){
23                     left++;
24                 }
25                 else if(tmpsum>target){
26                     right--;
27                 }else{
28                     right--;
29                     left++;
30                 }
31             }
32         }
33         return closest;
34     }
35 }

 

这个问题几乎和 3Sum 是一样的,我们但是这里是要找最为接近的三元组,所以选择的标准不一样而已,其他的一样。

 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         Arrays.sort(nums);
 4         int mindiff=Integer.MAX_VALUE;
 5         int closestsum=0;
 6         for(int i=0;i<nums.length;i++){
 7             int num1=nums[i];
 8             if(i>0&&num1==nums[i-1]){
 9                 continue;
10             }
11             for(int j=i+1;j<nums.length;j++){
12                 int num2=nums[j];
13                 if(j>i+1&&num2==nums[j-1]){
14                     continue;
15                 }
16                 for(int k=j+1;k<nums.length;k++){
17                     int num3=nums[k];
18                     if(k>j+1&&num3==nums[k-1]){
19                         continue;
20                     }
21                     int sum=num1+num2+num3;
22                     int diff=Math.abs(sum-target);
23                     if(diff<mindiff){
24                         mindiff=diff;
25                         closestsum=sum;
26                         if(diff==0) return sum;
27                     }
28                     if(sum>target){
29                         break;
30                     }
31                 }
32             }
33         }
34         return closestsum;
35     }
36 }

 

posted on 2015-08-12 20:23  F_G  阅读(201)  评论(0编辑  收藏  举报