LeetCode 15 输入无序、有重复,输出排重版 3-Sum

V1 粗暴的遍历,时间复杂度O(N³)

func threeSumClosest(nums []int, target int) int {
min := 0
result := 0
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
for k := j + 1; k < len(nums); k++ {
current := abs(nums[i] + nums[j] + nums[k] - target)
if k == 2 {
min = current
result = nums[i] + nums[j] + nums[k]
} else if current < min {
min = current
result = nums[i] + nums[j] + nums[k]
}
}
}
}
return result
} func abs(x int) int {
if x < 0 {
return 0 - x;
} else {
return x
}
}

V2 优化到O(N²)

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
}
}
上一篇:Linux下安装mysql教程


下一篇:java 多态 向上 向下转型