题目:
![](https://i-blog.csdnimg.cn/blog_migrate/28ba28a418c7a2672c43d4d50532b417.png)
解题思路:
![](https://i-blog.csdnimg.cn/blog_migrate/eebbcc56704ff1a3f7f46d2a456e2c98.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a5dc1db4716f0a1742a732f10fe30743.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e9b9158bcf16a06e337e11343dfd673a.png)
代码:
fun threeSumClosest(nums: IntArray, target: Int): Int {
nums.sort() // 从小到大排序
var result = 100000 // 超过最大值被减的时候就是最小值
for (first in 0 until nums.size) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue
}
var second = first + 1
var third = nums.size - 1
while (third > second) {
val sum = nums[first] + nums[second] + nums[third]
if (sum == target) {
return target
}
if (abs(target - sum) < abs(target - result)) {
result = sum
}
if (sum > target) {
third--
while (nums[third] == nums[third + 1] && third > second) {
third--
}
} else {
second++
while (nums[second] == nums[second - 1] && second < third) {
second++
}
}
}
}
return result
}