双指针 04

111 阅读1分钟

LeetCode 16

原题链接

代码如下:

/**
 * 排序 + 双指针
 * 
 * 现将数组升序排列 
 * 从头到倒数第三位遍历数组,
 * 每次遍历时 开头i,下一位i+1,末尾nums.length-1,三个位置组成和
 * 与target比较,如果大了,尾指针向前移动,小了,头指针向后移动 
 * 在这期间不断更新结果ans
 * 
 * Code by java
 */
class Solution {

	public int threeSumClosest(int[] nums, int target) {
		Arrays.sort(nums); // 升序排序
		int ans = 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 sum = nums[start] + nums[end] + nums[i]; // 本次遍历的和

				if (Math.abs(target - sum) < Math.abs(target - ans))
					ans = sum; // 发现更接近的结果

				if (sum > target) // 大了,尾指针前移
					end--;
				else if (sum < target) // 小了,头指针
					start++;
				else
					return ans; // 刚好相等,直接返回
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		int[] a = new int[] { -1, 2, 1, -4 };
		Solution k = new Solution();
		System.out.println(k.threeSumClosest(a, 1));
	}
}