Leetcode 16 3Sum Closest
阿新 • • 發佈:2019-01-01
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).
這個題和Leetcode15的思路基本類似,就是在前面那個題目的基礎上加上了一個判斷求值。
1)
import java.util.*; public class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int len = nums.length; if(len < 3){ return 0; } int Min = nums[0] + nums[1] + nums[2]; for(int left = 0 ; left < len - 2 ; left++){ int mid = left + 1; int right = len - 1; while(mid < right){ int tmp = target - nums[left]; if(Math.abs(Min - target) > Math.abs(tmp - nums[mid] - nums[right])) Min = nums[mid] + nums[left] + nums[right]; if(nums[mid] + nums[right] == tmp){ return target; }else if(nums[mid] + nums[right] < tmp){ mid++; }else{ right--; } } } return Min; } }
時間複雜度:O(n2)