zoukankan      html  css  js  c++  java
  • [LeetCode 016] 3Sum Closest

    3Sum Closest

    • 遍历数组nums,依次取出一个数nums[i],在i之后的数列中找两个数最接近target
      • 第一个数固定,后两个数按类似2Sum处理。
      • sum小于target时,需要将左边的数向右移动。
      • sum大于target时,需要将右边的数向左移动。
    • 设置midDif存储最小的difference,不断的跟新midDif
    • 设置result存储三个数的和,当midDif更新时,result也更新。

    Implementation

    public class Solution {
        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int minDif = Integer.MAX_VALUE;
            int result = 0;
            for (int i = 0; i < nums.length - 2; i++) {
                int left = i + 1;
                int right = nums.length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[left] + nums[right];
                    int dif = Math.abs(sum - target);
                    if (dif == 0)
                        return target;
                    if (sum > target) {
                        right--;
                    }
                    else {
                        left++;
                    }
                    if (dif < minDif) {
                        minDif = dif;
                        result = sum;
                    }
                }
            }
            return result;
        }
    }
    
  • 相关阅读:
    Navicat12激活,最新版本v12.1.18,原版激活[windows]
    【工具】Fiddler使用教程
    MongoDB笔记
    MongoDB
    MySQL三层结构、用户权限、索引设计原则
    Ajax
    linux简单优化
    linux基本
    Memcached
    Django+Uwsgi+Nginx
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5195302.html
Copyright © 2011-2022 走看看