代码改变世界

LeetCode 16 最接近的3Sum

2019-05-19 23:22  yx1989  阅读(137)  评论(0编辑  收藏  举报

3Sum Closest

Runtime: 4 ms
Memory Usage: 2.7 MB

func threeSumClosest(nums []int, target int) int {
	sort.Ints(nums)
	result := nums[0] + nums[1] + nums[len(nums)-1]
	n := len(nums)
	for i := 0; i < n-2; i++ {
		start := i + 1
		end := n - 1

		for start < end {
			current := nums[i] + nums[start] + nums[end]
			x := current - target
			if abs(x) < abs(result - target) {
				result = current
			}
			if x > 0 {
				end--
			} else if x < 0 {
				start++
			} else {
				break
			}
		}
	}
	return result
}

func abs(x int) int {
	if x < 0 {
		return 0 - x;
	} else {
		return x
	}
}