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;
        }
    }
    
  • 相关阅读:
    Java
    hadoop MapReduce Yarn运行机制
    在eclipse上开发hadoop2.5.2程序的快捷方法
    eclipse快捷键
    HDFS原理介绍
    Java异常
    hadoop初识
    操作系统学习---进程管理(二)
    操作系统学习---进程管理(一)
    操作系统学习---虚拟内存
  • 原文地址:https://www.cnblogs.com/clnsx/p/12240790.html
Copyright © 2011-2022 走看看