LeetCode : 3Sum Closest [java]

来源:互联网 发布:java web架构设计 编辑:程序博客网 时间:2024/05/17 01:26

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路:同上篇博客,稍加变化而已。

import java.util.Arrays;public class Solution {    public int threeSumClosest(int[] nums, int target) {if (nums.length < 3) {return 0;}Arrays.sort(nums);int value = nums[0] + nums[1] + nums[2];for (int i = 0; i < nums.length; i++) {if (i >= 1 && nums[i] == nums[i - 1]) {continue;}int j = i + 1;int k = nums.length - 1;while (j < k) {int nowValue = nums[i] + nums[j] + nums[k];if (Math.abs(nowValue - target) < Math.abs(value - target)) {value = nowValue;}if (nowValue > target) {while (k > j && k <= nums.length - 2 && nums[k] == nums[k - 1]) {k--;}k--;} else if (nowValue < target) {while (j < k && j >= 1 && nums[j] == nums[j + 1]) {j++;}j++;} else {return target;}}}return value;    }}


1 0
原创粉丝点击