leetcode 3Sum Closest 难度系数3 3.7

来源:互联网 发布:域名收费标准 编辑:程序博客网 时间:2024/06/15 22:47

Question:

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).
public class Solution {private int result;private int state;public int threeSumClosest(int[] num, int target) {result = 0;Arrays.sort(num);state = 0;if (num.length < 3) {return result;}int length = num.length - 1;for (int i = 0; i <= length - 2; i++) {if (i != 0 && (num[i] == num[i - 1])) {continue;}subThreeSum(num, i, i + 1, length, target);}return result;}private void subThreeSum(int[] num, int i, int first, int last, int target) {while (first < last) {int sum = num[i] + num[first] + num[last];if (state == 0|| Math.abs(sum - target) < Math.abs(result - target)) {result = sum;state = 1;}if (sum <= target) {first++;while (first < last && num[first] == num[first - 1]) {first++;}} else {last--;while (first < last && num[last] == num[last + 1]) {last--;}}}}}


0 0
原创粉丝点击