zoukankan      html  css  js  c++  java
  • 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 int threeSumClosest(int[] nums, int target) {
            int length = nums.length;
            Arrays.sort(nums);
            int diff=Integer.MAX_VALUE;
            int sumclosest=Integer.MAX_VALUE;
            for (int i = 0; i < length-2; i++) {
                if(i>0&&nums[i]==nums[i-1]){
                    continue;
                }
                int head = i+1;
                int tail = length-1;
                while (head<tail){
                    int tmp = nums[i]+nums[head]+nums[tail];
                    int newdiff = Math.abs(tmp-target);
                    if (diff>newdiff){
                        diff = newdiff;
                        sumclosest = tmp;
                    }
                    if (tmp<target){
                        head++;
                    }
                    else if (tmp>target){
                        tail--;
                    }
                    else {
                        int k=head+1;
                        while (k<tail&&nums[k]==nums[k-1]){
                            k++;
                        }
                        head = k;
                        int l=tail-1;
                        while (l>head&&nums[l]==nums[l+1]){
                            l--;
                        }
                        tail = l;
                    }
                }
            }
            return sumclosest;
        }
    
  • 相关阅读:
    BBS项目
    form组件
    auth模块
    模板语言
    内置auth 的使用,用超级用户创建
    django文件上传
    django序列化问题
    SPI Flash的操作
    输入捕获实验
    uc os相关的C语言知识点1-函数指针
  • 原文地址:https://www.cnblogs.com/bingo2-here/p/7873134.html
Copyright © 2011-2022 走看看