跟之前几个题思路大致相同,
贪心中的双指针法class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int min = Integer.MAX_VALUE; int ans = 0; int flag = 0; for (int base = 0; base < nums.length; base++) { int i = base + 1, j = nums.length - 1; if (flag == 1) break; while (i < j) { int tmp = nums[base] + nums[i] + nums[j]; if (Math.abs(tmp - target) < min) { ans = tmp; min = Math.abs(tmp - target); } if (tmp > target) { j--; } else if (tmp < target) { i++; } else { flag = 1; break; } } } return ans; }}
更新:
观摩了下榜单第一老哥的代码,写的不错,比我的快了许多:class Solution { public int threeSumClosest(int[] nums, int target) { int n = nums.length; Arrays.sort(nums); int less = nums[0] + nums[1] + nums[2]; int more = nums[n-3] + nums[n-2] + nums[n-1]; if (less >= target) return less; if (more <= target) return more; for (int i = 0; i < n - 2; i++){ int min = nums[i] + nums[i+1] + nums[i+2]; int max = nums[i] + nums[n-2] + nums[n-1]; if (min > target){ more = Math.min(more, min); break; } if (max < target){ less = Math.max(less, max); continue; } int j = i + 1, k = n - 1; while(j < k){ int sum = nums[i] + nums[j] + nums[k]; if(sum == target) return target; else if(sum > target){ more = Math.min(more, sum); while(--k > j && nums[k]==nums[k+1]); }else{ less = Math.max(less, sum); while(++j < k && nums[j]==nums[j-1]); } } } return more - target > target - less ? less : more; }}