zoukankan      html  css  js  c++  java
  • leetcode 16 3Sum Closest

    题目内容

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    Example:
    Given array nums = [-1, 2, 1, -4], and target = 1.
    
    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
    

    分析过程

    • 题目归类:
      数组,遍历,夹逼
    • 题目分析:
      此题和之前的3sum很相似,只要用一个变量 sum 保存最近的值就可以。依旧先排序后使用ijk来夹逼最近的值。
    • 边界分析:
      • 空值分析
        nums为空
      • 循环边界分析
        i<nums.length
        j=i+1,j < nums.length
        k=nums.length-1,j<k
    • 方法分析:
      • 数据结构分析
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建
      [0,0,0] 0,
      [1,1,-1,1,-2,3]

    代码实现

    import java.util.*;
    class Solution {
        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int sum = 0;
            boolean firstFlag = true;
            for(int i = 0; i < nums.length-2; i++) {
                int j = i+1;
                int k = nums.length-1;
                while(j<k){
                    int tmpSum = nums[i]+nums[j]+nums[k];
                    if(firstFlag == true){
                        sum = tmpSum;
                        firstFlag = false;
                        
                    }else if(Math.abs(target-sum)>Math.abs(target-tmpSum)){
                        sum = tmpSum;
                    }
                    if(tmpSum==target){
                            return target;
                    }else if(tmpSum > target){
                            k--;
                    }else{
                            j++;
                    }
                }
            }
            return sum;
        }
    }
    
  • 相关阅读:
    微软的十年之变
    如何在易受攻击的SSD上禁用硬件BitLocker加密
    Tech Summit 2018见闻:我们,MVP
    Tech Summit 2018见闻:IT之家读者捕捉铺路集团董事长玄隐
    Windows 10怎么了?
    循环队列
    模拟键盘事件
    模拟鼠标事件
    进程间通信——— 匿名管道
    进程间通信——— LPC
  • 原文地址:https://www.cnblogs.com/clnsx/p/12240790.html
Copyright © 2011-2022 走看看