Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最接近的三数之和,代码有误 #67

Open
silves-xiang opened this issue Oct 16, 2022 · 0 comments
Open

最接近的三数之和,代码有误 #67

silves-xiang opened this issue Oct 16, 2022 · 0 comments

Comments

@silves-xiang
Copy link
Contributor

silves-xiang commented Oct 16, 2022

`
func threeSumClosest(nums []int, target int) int {
if len(nums) == 3 {
return nums[0] + nums[1] + nums[2]
}
sort.Ints(nums)
sum := nums[0] + nums[1] + nums[2]

  for i := 0; i < len(nums); i++ {
	  l := i+1
	  r := len(nums) - 1
	  for l < r {
		  current := nums[i] + nums[l] + nums[r]
		  if math.Abs(float64(sum - target)) > math.Abs(float64(target - current)) {
			  sum = current
		  }
		  if current < target {
			  l++
		  } else if current == target {
			  return target
		  } else {
			  r--
		  }
	  }
  }
  return sum

}

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant