【LeetCode OJ 016】3Sum Closest
阿新 • • 發佈:2017-07-30
i+1 tco margin .so data style 鏈接 util imp
解題思路:先對數組進行排序,然後遍歷數組。尋找和最接近target的數。
題目鏈接:https://leetcode.com/problems/3sum-closest/
題目: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) { int length=nums.length; int minNum=Integer.MAX_VALUE; int tempsubNum=Integer.MAX_VALUE; Arrays.sort(nums);//先對nums進行排序 for(int i=0;i<length-2;i++) { //略過同樣的數 if(i!=0&&nums[i]==nums[i-1]) { continue; } int left=i+1; int right=length-1; while(left<right) { int a1=nums[left]; int a2=nums[right]; int sum=a1+a2+nums[i]; int subNum=Math.abs(sum-target); //當前的和值sum離target更近一點 if(subNum<=tempsubNum) { tempsubNum=subNum; //保存這一步中的sum-target的差值 minNum=sum; } if(sum-target<0) //說明sum<target, left++; else right--; } } return minNum; } }
【LeetCode OJ 016】3Sum Closest