题目链接

思路

和上一道题一样,先排序,再用双指针法遍历。

代码

  1. import kotlin.math.abs
  2. class Solution {
  3. fun threeSumClosest(nums: IntArray, target: Int): Int {
  4. var result = nums[0] + nums[1] + nums[2]
  5. var sub = abs(result - target)
  6. nums.sort()
  7. for (i in 0 until nums.size - 2) {
  8. var pLeft = i + 1
  9. var pRight = nums.size - 1
  10. while (pLeft < pRight) {
  11. val sum = nums[i] + nums[pLeft] + nums[pRight]
  12. val res = sum - target
  13. val nowSub = abs(sum - target)
  14. if (nowSub < sub) {
  15. result = sum
  16. sub = nowSub
  17. }
  18. if (res == 0) {
  19. return target
  20. }else if (res > 0) {
  21. pRight--
  22. }else {
  23. pLeft++
  24. }
  25. }
  26. }
  27. return result
  28. }
  29. }