LeetCode16. 最接近的三数之和
作者:互联网
一、题目描述
☆☆☆二、解法
思路:与15题三数之和类似, 排序+双指针。
class Solution { public int threeSumClosest(int[] nums, int target) { /** * 方法1: 排序 + 暴力法, 时间复杂度O(n^3) */ /*Arrays.sort(nums); int diff = Integer.MAX_VALUE; for (int i = 0; i < nums.length - 2; i++) { if (i > 0 && nums[i] == nums[i-1]) continue; for (int j = i + 1; j < nums.length - 1; j++) { if (j > i + 1 && nums[j] == nums[j-1]) continue; for (int k = j + 1; k < nums.length; k++) { if (k > j + 1 && nums[k] == nums[k-1]) continue; int tempDiff = nums[i] + nums[j] + nums[k] - target; diff = Math.abs(diff) < Math.abs(tempDiff) ? diff : tempDiff; } } } return target + diff;*/ /** * 方法2:排序 + 对撞指针, 时间复杂度: O(n^2) */ Arrays.sort(nums); int closeNum = nums[0] + nums[1] + nums[2]; // 注意此初始化 for (int i = 0; i < nums.length - 2; i++) { if (i > 0 && nums[i] == nums[i-1]) continue; int start = i + 1, end = nums.length - 1; while (start < end) { int tempSum = nums[i] + nums[start] + nums[end]; if (tempSum == target) { // 如果和为 target,肯定是最接近的 return target; } if (Math.abs(tempSum - target) < Math.abs(closeNum - target)) { closeNum = tempSum; } if (tempSum > target) { end --; }else { start ++; } } } return closeNum; } }
标签:target,nums,int,三数,++,tempSum,LeetCode16,diff,接近 来源: https://www.cnblogs.com/HuangYJ/p/14117559.html