zoukankan      html  css  js  c++  java
  • 16. 3Sum Closest (JAVA)

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    Example:

    Given array nums = [-1, 2, 1, -4], and target = 1.
    
    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
    class Solution {
        public int threeSumClosest(int[] nums, int target) {
            if(nums.length<3) return 0;
    
            int sum;
            int ret=nums[0]+nums[1]+nums[2]; //initialize return value
            int len = nums.length-2;
            int left; //point to the left side of the array
            int right; //point to the right side of the array
            
            Arrays.sort(nums);
            
            for(int i = 0; i < len; i++){
                left = i+1;
                right = len+1;
                
                while(left < right){
                    sum = nums[i] + nums[left] + nums[right];
                    if(sum > target){
                        right--;
                    }
                    else if(sum < target){
                        left++;
                    }
                    else{
                        return target;
                    }
                    
                    if(Math.abs(target - sum) < Math.abs(target - ret)) ret = sum;
                }
                
                //skip repeated digital
                while(nums[i] == nums[i+1]) {
                    if(i+1 >= len) break;
                    i++; 
                }
            }
            return ret;
        }
    }
  • 相关阅读:
    xml文档格式学习笔记
    Visual Studio学习记录
    Java学习笔记
    C#项目学习记录
    Linux命令行与shell脚本编程大全 学习笔记
    NodeJS (npm) 学习笔记
    Angular学习笔记
    TypeScript学习笔记
    java 项目相关 学习记录
    docker学习记录
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10771678.html
Copyright © 2011-2022 走看看