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;
        }
    }
  • 相关阅读:
    红帽7 创建网络会话
    红帽7 Iptables与Firewalld防火墙
    红帽7 配置网卡
    红帽7 LVM逻辑卷管理器
    红帽7 RAID磁盘冗余阵列
    红帽7 磁盘划分
    wpf学习一(转)
    选中当前点击的位置
    c#客显
    两个程序间的通信有三种
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10771678.html
Copyright © 2011-2022 走看看