題目:Given an arraySofnintegers, find three integers inSsuch 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).解題思路:先對數組進行排序,然後遍歷數組,尋找和最接近target的數。示例代碼:
import java.util.Arrays; public class Solution { public int threeSumClosest(int[] nums, int target) { int length=nums.length; int minNum=Integer.MAX_VALUE; int tempsubNum=Integer.MAX_VALUE; Arrays.sort(nums);//先對nums進行排序 for(int i=0;i