Problem Description:
Given an arrayS of n integers, find three integers in S such so the sum is closest to a Given Number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1.
The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Problem Analysis: The problem with 3Sums, that is, the basic problem of conversion to 2Sum , here added a flag to record the minimum gap value can be;
Code:
public class Solution {public int threesumclosest (int[] num, int target) {/**** handles boundary value case *****/if (num = = NULL | | Num.length = = 0) return 0;int result = 0;if (num.length <= 3) {for (int data:num) result + = Data;return result; First-time sorting quicksort (num, 0, num.length-1),//arrays.sort (num), int min_distance = minimum value of integer.max_value;//record and target value int Temp_target = 0;//current target value int temp_distance = 0;for (int i = 0; i < num.length-2; i++) {temp_target = Target-num[i];int Start = i + 1;int end = Num.length-1;while (Start < end) {int temp_sum = Num[start] + num[end];if (temp_sum = = Temp_tar Get) {return target;} else if (Temp_sum < temp_target) {++start;temp_distance = Temp_target-temp_sum;} Else{--end;temp_distance = Temp_sum-temp_target;} if (Temp_distance < min_distance) {min_distance = Temp_distance;result = Temp_sum + Num[i];}}} return result; }/* First write quick sort */private void QuickSort (int[] data,int Start,int end) {if (Start < end) {int mid = partition (data, start, end); q Uicksort (data,Start, mid-1); QuickSort (Data,mid + 1, end);}} private int partition (int[] data, int start,int end) {int mid_data = data[end];//Select Sentinel int index = start;for (int i = start; I < end; i++) {if (Data[i] < Mid_data) {Swap (data, index, i); + + Index;}} Swap (data, index, end); return index;} Swap two value data in array private void Swap (int[] data, int a, int b) {int temp = Data[a];d ata[a] = data[b];d ata[b] = temp;}}
Leetcode-16 3Sum Closest