zoukankan      html  css  js  c++  java
  • [leedcode 16] 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).

    public class Solution {
        public int threeSumClosest(int[] nums, int target) {
            //本题是3Sum的变形,找出最接近target的值
            //跟3Sum唯一的不同是,需要增加一个变量min(注意初始化值),内层每次循环时,需要与它进行比较。保留住距离target最小的值
            //判断重复的逻辑可有可无,因为本题的输出只是需要返回总结果
            Arrays.sort(nums);
            int res=0;
            int min=Integer.MAX_VALUE;
            for(int i=0;i<nums.length;i++){
                int left=i+1;
               // if(i>0&&nums[i]==nums[i-1])continue;
                int right=nums.length-1;
                while(left<right){
                    int temp=nums[i]+nums[left]+nums[right];//注意局部变量的声明,为后面的循环简化表达式
                    if(temp==target)
                             return res=target;
                    if(temp>target){
                        if(temp-target<min){
                            res=temp;
                            min=res-target;
                        }
                              
                        right--;
                    }else{
                         if((target-temp)<min){
                              res=temp;
                              min=target-res;
                         }
                             
                        left++;
                    }
    
                }
            }
            return res;
        }
    }
  • 相关阅读:
    爬虫基础 2.1 http原理
    爬虫基础 2.1 http原理
    3.29上午
    3.28
    3.27下午
    3.27上午
    3.24上午
    3.23下午
    3.23上午
    3.22上午
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4626458.html
Copyright © 2011-2022 走看看