标签:
问题描述:
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).
问题分析:问题同3Sums,即转化为2Sum的基本问题,这里添加了一个标志进行记录最小差距的值即可;
代码:
public class Solution { public int threeSumClosest(int[] num, int target) { /****处理边界值情况*****/ if(num == null || num.length == 0) return 0; int result = 0; if(num.length <= 3) { for(int data : num) result += data; return result; } //先进行一次排序 quickSort(num, 0 , num.length - 1); //Arrays.sort(num); int min_distance = Integer.MAX_VALUE;//记录与目标值之间的最小值 int temp_target = 0;//当前的目标值 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_target) { 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; } /*先写快速排序*/ private void quickSort(int[] data,int start,int end) { if(start < end) { int mid = partition(data, start, end); quickSort(data, start, mid - 1); quickSort(data,mid + 1, end); } } private int partition(int[] data, int start,int end) { int mid_data = data[end];//选取哨兵 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; } //交换数组中的两个值数据 private void swap(int[] data, int a, int b) { int temp = data[a]; data[a] = data[b]; data[b] = temp; } }
标签:
原文地址:http://blog.csdn.net/woliuyunyicai/article/details/45008157