最接近的三数之和

Leetcode
2019-11-28 01:55
func threeSumClosest(nums []int, target int) int {
	L := len(nums)

	for i := 0; i < L; i++ {
		min := i
		for j := i; j < L; j++ {
			if nums[j] < nums[min] {
				min = j
			}
		}
		t := nums[i]
		nums[i] = nums[min]
		nums[min] = t
	}

	var result int = nums[0] + nums[1] + nums[2]
	var minDiff int = abs(result - target)
	for i := 0; i < L; i++ {
		t := nums[i]
		l, r := i+1, L-1
		for l < r {
			sum := t + nums[l] + nums[r]
			diff := abs(sum - target)
			if diff < minDiff {
				minDiff = diff
				result = sum
			} else if diff == 0 {
				return sum
			}
			if sum-target > 0 {
				r--
			} else {
				l++
			}
		}
	}
	return result
}

func abs(value int) int {
	if value < 0 {
		return -value
	}
	return value
}
验证码