問題: 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.git
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).
複製代碼
方法: 最原始的方法是三層循環遍歷,求全部三個數的sum,而後找出最接近target的sum,可是這樣的算法複雜度比較高,須要O(n^3)的時間複雜度,經過排序能夠下降比較的次數,先對數組進行排序,由於數組有序,若是sum大於target就從後面移動index,若是sum小於target就從前面移動index,向中間逼近,這樣就能夠減小比較的次數,這樣的算法時間複雜度是O(n^2)github
具體實現:算法
class ThreeSumClosest {
// -4, -1, 2, 1,
// 雙逼近算法
fun threeSumClosest(nums: IntArray, target: Int): Int {
var sum = nums[0] + nums[1] + nums[2]
nums.sort()
for (x in nums.indices) {
var i = x + 1
var j = nums.lastIndex
while (i < j) {
val curSum = nums[i] + nums[j] + nums[x]
val curDiff = abs(sum - target)
val diff = abs(curSum - target)
if (diff < curDiff) {
sum = curSum
}
if (curSum - target > 0) {
j--
} else if(curSum - target < 0) {
i++
} else {
return sum
}
}
}
return sum
}
}
fun main(args: Array<String>) {
val nums = intArrayOf(0,2,1,-3)
val target = 1
val threeSumClosest = ThreeSumClosest()
println(threeSumClosest.threeSumClosest(nums, target))
}
複製代碼
有問題隨時溝通數組
具體代碼實現能夠參考Githubbash