• [leetcode] 16. 最接近的三数之和


    跟之前几个题思路大致相同,
    贪心中的双指针法

    class Solution {
        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
    
            int min = Integer.MAX_VALUE;
            int ans = 0;
            int flag = 0;
    
            for (int base = 0; base < nums.length; base++) {
                int i = base + 1, j = nums.length - 1;
                if (flag == 1) break;
                while (i < j) {
                    int tmp = nums[base] + nums[i] + nums[j];
                    if (Math.abs(tmp - target) < min) {
                        ans = tmp;
                        min = Math.abs(tmp - target);
                    }
                    if (tmp > target) {
                        j--;
                    } else if (tmp < target) {
                        i++;
                    } else {
                        flag = 1;
                        break;
                    }
                }
            }
    
            return ans;
    
        }
    }
    

    更新:
    观摩了下榜单第一老哥的代码,写的不错,比我的快了许多:

    class Solution {
        public int threeSumClosest(int[] nums, int target) {
            int n = nums.length;
            Arrays.sort(nums);
            int less = nums[0] + nums[1] + nums[2];
            int more = nums[n-3] + nums[n-2] + nums[n-1];
            if (less >= target)
                return less;
            if (more <= target)
                return more;
            for (int i = 0; i < n - 2; i++){
                int min = nums[i] + nums[i+1] + nums[i+2];
                int max = nums[i] + nums[n-2] + nums[n-1];
                if (min > target){
                    more = Math.min(more, min);
                    break;
                }
                if (max < target){
                    less = Math.max(less, max);
                    continue;
                }
                int j = i + 1, k = n - 1;
                while(j < k){
                    int sum = nums[i] + nums[j] + nums[k];
                    if(sum == target) return target;
                    else if(sum > target){
                        more = Math.min(more, sum);
                        while(--k > j && nums[k]==nums[k+1]);
                    }else{
                        less = Math.max(less, sum);
                        while(++j < k && nums[j]==nums[j-1]);
                    }
                }
            }
            return more - target > target - less ? less : more;
        }
    }
    
  • 相关阅读:
    Asp.Net 构架(Http Handler 介绍) Part.2<转>
    大数据插入<转>
    网站开发技巧参考大全<转>
    qq校友好东西
    SQL2005存储过程解密 <转>
    用Lucene.net对数据库建立索引及搜索<转>
    用SharpDevelop3调试ASP.NET的方法
    【转】卢彦的利用xml实现通用web报表打印
    张仰彪第二排序法 <转>
    依赖注入那些事儿 <转>
  • 原文地址:https://www.cnblogs.com/acbingo/p/9250343.html
Copyright © 2020-2023  润新知