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;
    }
}
原文地址:https://www.cnblogs.com/clnsx/p/12240790.html