标签:+= sum code 排序 nbsp sort color solution array
先排序,然后双指针。
class Solution { public int threeSumClosest(int[] nums, int target) { int res = nums[0]+nums[1]+nums[2]; Arrays.sort(nums); for(int i=0;i<nums.length;i++){ int start = i+1; int end = nums.length-1; while(start < end){ int num_sum = nums[i]+nums[start]+nums[end]; if(Math.abs(num_sum-target)<Math.abs(res-target)){ res = num_sum; } if(num_sum<target){ start++; }else if(num_sum>target){ end--; }else{ return num_sum; } } } return res; } }
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() res = nums[0]+nums[1]+nums[2] for i in range(len(nums)): start = i+1 end = len(nums)-1 while start < end: num_sum = nums[i] + nums[start] + nums[end] if abs(num_sum-target) < abs(res-target): res = num_sum if num_sum < target: start+=1 elif num_sum > target: end-=1 else: return res return res
标签:+= sum code 排序 nbsp sort color solution array
原文地址:https://www.cnblogs.com/huangzengrui/p/12426421.html