leetcode刷題記錄Array篇(16~3 Sum closest)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

題目:Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

翻譯:給定n個整數的數組S,在S中找到三個整數,使得和最接近一個給定的數目target。 返回三個整數的總和。 你可以假設每個輸入都只有一個解決方案。

思路:這題的思路和15題3sum差不多,只是結果變成最接近某個數,而不是等於0,並且只需要返回最小的結果,斌不需要篩除相同的結果,所以該題在細節上的處理並沒有之前那道題多。
1.先排序,給結果一個初始值
2.迴圈遍曆數組,對當前下標索引之後的元素進行首尾遍曆,即low,high
3.當nums[i]+nums[low]+nums[high]-target的絕對值小於result-target的絕對值,則把當前的sum賦值給result
4.當sum>target,則需要把sum的值減小,使得sum更接近target,則要把high--,當sum<target,low++

golang代碼:

package main import (      "fmt"      "sort"  )  func main() {      nums := []int{1, 2, 5, 13, -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 //三個數組相加的值      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}  //求絕對值  func abs(a int) int {      if a < 0 {          return -a      }      if a == 0 {          return 0      }      return a  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.