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;
        }
    }
    
  • 相关阅读:
    mybatis几种开发方式
    SpringData,JPA,MongoDB,Solr,Elasticsearch底层逻辑关系
    简论远程通信(RPC,Webservice,RMI,JMS的区别)
    spring/spring boot/spring mvc中用到的注解
    Centos常用命名
    Mybatis详解
    Java成长之路
    Hibernate 与Mybatis之比较
    Struts2 与SpringMVC之比较
    Maven 配置文件详解
  • 原文地址:https://www.cnblogs.com/clnsx/p/12240790.html
Copyright © 2011-2022 走看看