zoukankan      html  css  js  c++  java
  • 离给定整数最近的三数之和

    1. 问题描述

      leetcode 16,求出离给定目标整数最近的三数之和
    2. 解决思路

      和三数之和思路一致,额外需要解决的就是保存两个标志整数,用来标志小于target的最大数和大于target的最小数。
    3. 注意事项

      注意一些边界条件以及运算的溢出情况。
       1 import java.util.Arrays;
       2 
       3 public class Solution {
       4     public static int threeSumClosest(int[] nums, int target) {
       5         Arrays.sort(nums);
       6         int length = nums.length;
       7         int leftP;
       8         int minT = nums[0] + nums[1] + nums[2] < target ? nums[0] + nums[1] + nums[2]: Integer.MIN_VALUE+1;
       9         int maxT = nums[length-1] + nums[length-2] + nums[length-3] > target ? nums[length-1] + nums[length-2] + nums[length-3] : Integer.MAX_VALUE;
      10         for(int i=0; i<length-2; i++){
      11             // 最外层的去重方法
      12             if(i>0 && nums[i]==nums[i-1]) {
      13                 continue;
      14             }
      15             leftP = i+1;
      16             int rightP = length-1;
      17             while(leftP<rightP) {
      18                 int temp = nums[i] + nums[leftP] + nums[rightP];
      19                 if (temp < target) {
      20                     minT = minT > temp ? minT : temp;
      21                     leftP += 1;
      22 
      23                 } else if (temp > target) {
      24                     maxT = maxT > temp ? temp : maxT;
      25                     rightP -= 1;
      26                 } else if (temp == target){
      27                     return target;
      28                 }
      29             }
      30         }
      31         return  ((long)maxT-target) > ((long)target-minT) ? minT : maxT;
      32     }
      33 }
  • 相关阅读:
    UVA 120 Stacks of Flapjacks
    HDU 4869 Turn the pokers
    HDU 4882 ZCC Loves Codefires
    HDU 4864 Task
    HDU 4861 Couple doubi
    UVA 1600 Patrol Robot
    UVA 712 S-Trees
    2014/4/6长沙多校第六次(浙大校赛)
    UVA10905 思维考察
    HDU1498 枚举+二分图类棋盘问题(最大匹配)
  • 原文地址:https://www.cnblogs.com/dogeLife/p/10913667.html
Copyright © 2011-2022 走看看