1. 程式人生 > >LeetCode(16)-3Sum Closest

LeetCode(16)-3Sum Closest

16. 3Sum Closest

Given an array nums of n integers and an integer target, find three >integers in nums such that the sum is closest to target. Return the >sum of the three integers. You may assume that each input would >have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

題目的意思就是:給一個整形陣列,然後找出裡面的三個數字之和的結果與target最接近,並輸出這個結果。嗯我的思路很簡單,窮舉出所有結果然後比較。這種思路有點low,有點耗時,不過還算通過測試了,先暫時貼上吧,後面再來研究大神的程式碼。

public int threeSumClosest(int[] nums, int target) {
       int min=Integer.MAX_VALUE;
       for (int i = 0; i <
nums.length; i++) { for (int j =i+1; j <nums.length; j++) { for (int k = 0; k <nums.length; k++) { int sum=nums[i]+nums[j]+nums[k]; min=Math.min(Math.abs(sum-target),min); } } } return min; }