1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
}