zoukankan      html  css  js  c++  java
  • LeetCode(16) - 3Sum Closest

      这一题和leetCode(15)的3sum基本上一个思路 —— two pointer。而且题目保证只有有一个答案,所以还不需要考虑重复的问题,只需要维护一个与target差值最小的closeDistance,以及对应的数组上的值就好。

      代码如下:

      

     1 public class Solution {
     2     public int threeSumClosest(int[] nums, int target) {
     3         //先排序
     4         Arrays.sort(nums);
     5         int minDistance = Integer.MAX_VALUE;
     6         int result = 0;
     7         for (int i = 0; i < nums.length;i++) {
     8             int head = i + 1;
     9             int tail = nums.length - 1;
    10             while(head < tail) {
    11                 int sum = nums[i] + nums[head] + nums[tail];
    12                 int currDis = Math.abs(sum - target);
    13                 //判断当前差值是否比最小差值要小,如果是,则更新minDistance和result
    14                 if (currDis <= minDistance) {
    15                     result = sum;
    16                     minDistance = currDis;
    17                 }
    18                 if (sum < target) head++;
    19                 else if (sum > target) tail--;
    20                 //差值为0,已经是最小,故直接返回
    21                 else return sum;
    22             }
    23         }
    24         return result;
    25     }
    26 }
  • 相关阅读:
    基于组的策略(GBP)开启新型网络设计时代
    49 多维数组(二维数组)
    48 查找
    47 排序
    46 字符数组和字符串
    45 数组应用
    44 数组
    43 C语言宏定义
    42 预处理命令
    41 函数封装练习
  • 原文地址:https://www.cnblogs.com/kepuCS/p/5271549.html
Copyright © 2011-2022 走看看