LeetCode16

来源:互联网 发布:山寨网络机顶盒 编辑:程序博客网 时间:2024/05/22 15:37

【题目】

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

【思路】

很显然与第15题相关,查找方法也与15题差不多,只是要判断当前组合是否比之前所有组合中,与目标值差最小的一组哪一组更符合需求,决定是否替换即可。

【Java代码】

public class Solution_16_3Sum_closest {public int threeSumClosest(int[] nums, int target){Arrays.sort(nums);int result = nums[0] + nums[1] + nums[2];for(int i = 0 ; i < nums.length - 2 ; i++){int start = i+1, end = nums.length - 1;while(start < end){int curr = nums[i] + nums[start] + nums[end];if(curr < target)start++;else if(curr > target) end--;elsereturn target;if(Math.abs(target - result) > Math.abs(target - curr))result = curr;}}return result;}}

【大佬】

该题第一名的大佬,是直接复用了第15题的代码,以目标为中心,向+1 和 -1 两个方向,逐一判断是否存在三个数的和等于当前新的目标值,如果有,就返回该目标值即可。

原创粉丝点击