Leetcode Brush Title Record Array (16~3 Sum closest)

Source: Internet
Author: User
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}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.