This is a creation in
Article, where the information may have evolved or changed.
Title: Given An array S of n integers, find three integers in S such so the sum is closest to a Given number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
Translation: a given n integer array s, found in S three integers, making and closest to a given number of target. Returns the sum of three integers. You can assume that each input has only one solution.
Idea: The idea of this problem and 15 3sum is almost, only the result becomes the closest to a certain number, instead of equal to 0, and only need to return the smallest results, bin does not need to screen the same results, so the problem in the details of the treatment is not before that problem more.
1. First order, give the result an initial value
2. Iterate through the array, iterating through the elements after the current subscript index, i.e. Low,high
3. When the absolute value of the nums[i]+nums[low]+nums[high]-target is less than the value of Result-target, the current sum is assigned to result
4. When sum>target, it is necessary to reduce the sum value, so that the sum closer to target, then the high--, when the sum<target,low++
Golang Code:
Package Main import ("FMT" "sort") Func main () {nums: = []int{1, 2, 5, 1, 3} fmt. Println (Threesumclosest (Nums, 5))} func threesumclosest (nums []int, target int) int {sort. Ints (nums) Arrlen: = Len (nums) Result: = Nums[0] + nums[1] + nums[arrlen-1] var sum int//three array add value if Len (Nums) < 3 {return 0} for I: = 0; i < Arrlen; i++ {low, High: = I+1, arrLen-1 for low < high {sum = Nums[i] + Nums[low] + Nums[high] if sum ; Target {high--} else {low++} if ABS (Sum-target) < ABS (Result-target) { result = sum}}} return result}//Seek absolute value func abs (a int) int {If a < 0 {retur N-A} If A = = 0 {return 0} return a}