zoukankan      html  css  js  c++  java
  • [Swift]LeetCode16. 最接近的三数之和 | 3Sum Closest

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/9885069.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    Example:

    Given array nums = [-1, 2, 1, -4], and target = 1.
    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

    例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
    与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

    24ms
     1 class Solution {
     2     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     3         if (nums.count < 3) {
     4             return 0
     5         }
     6         var result = Int.max
     7         var sortedNums = nums.sorted(by: <)
     8         for index in 0..<(nums.count - 2) {
     9             if index == 0 || sortedNums[index] != sortedNums[index - 1] {
    10                 var firstNum = sortedNums[index]
    11                 var startIndex = index + 1
    12                 var endIndex = nums.count - 1
    13                 while(startIndex < endIndex) {
    14                     var temp = firstNum + sortedNums[startIndex] + sortedNums[endIndex]
    15                     
    16                     if (result == Int.max || abs(temp - target) < abs(result - target)) {
    17                         result = temp
    18                     }
    19                     if (temp > target) {
    20                             endIndex -= 1
    21                     } else if (temp < target) {
    22                             startIndex += 1
    23                     } else {
    24                         return temp
    25                     }
    26                 }
    27             }
    28         }
    29         return result
    30     }
    31 }

    24ms

     1 class Solution {
     2     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     3         if(nums.count < 3){
     4             var result = 0
     5             for value in nums {
     6                 result = result + value
     7             }
     8             return result;
     9         }
    10         var tempNums = nums.sorted{$0<$1}
    11         let count = tempNums.count
    12         var threeSum = tempNums[0] + tempNums[1] + tempNums[2]
    13         // print(tempNums)
    14         for indexF in 0 ..< count {
    15             if (indexF != 0) && (tempNums[indexF] == tempNums[indexF - 1]){
    16                 continue
    17             }
    18             let tempArray = self.aFunction(numbers: tempNums, begin: indexF + 1, end: count)
    19             //            print(tempArray)
    20             var left:Int = 0
    21             var right:Int = tempArray.count - 1
    22             while left < right {
    23                 // print(threeSum)
    24                 var newOffsetValue = tempArray[left] + tempArray[right] + tempNums[indexF] - target
    25                 
    26                 if(newOffsetValue == 0){
    27                     return target;
    28                 }
    29                 
    30                 if(threeSum - target < 0){
    31                     if(newOffsetValue < 0){
    32                         if(newOffsetValue + target > threeSum){
    33                             threeSum = tempArray[left] + tempArray[right] + tempNums[indexF]
    34                             left = left + 1
    35                         }else{
    36                             left = left + 1
    37                         }
    38                     }else{
    39                         if(abs(newOffsetValue) < abs(threeSum - target)){
    40                             threeSum = tempArray[left] + tempArray[right] + tempNums[indexF]
    41                             right = right - 1
    42                         }else{
    43                             right = right - 1
    44                         }
    45                     }
    46                 }else{
    47                     if(newOffsetValue < 0){
    48                         if(abs(newOffsetValue) < abs(threeSum - target)){
    49                             threeSum = tempArray[left] + tempArray[right] + tempNums[indexF]
    50                             left = left + 1
    51                         }else{
    52                             left = left + 1
    53                         }
    54                     }else{
    55                         if(newOffsetValue + target  < threeSum){
    56                             threeSum = tempArray[left] + tempArray[right] + tempNums[indexF]
    57                             right = right - 1
    58                         }else{
    59                             right = right - 1
    60                         }
    61                     }
    62                 }
    63             }
    64         }
    65         return threeSum
    66     }
    67     
    68     
    69     func aFunction(numbers: Array<Int>, begin: Int, end: Int) -> Array<Int> {
    70         let newNumbers = Array(numbers[begin..<end])
    71         return newNumbers
    72     }
    73     
    74 }

    28ms

     1 class Solution {
     2     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     3         let count = nums.count 
     4         guard count > 2 else { return 0 }
     5         let nums = nums.sorted()
     6         
     7         var close = Int.max
     8         for i in 0..<count - 2 {
     9             if i > 0 && nums[i] == nums[i - 1] {
    10                 continue
    11             }
    12             
    13             var twoSum = target - nums[i]
    14             var left = i + 1, right = count - 1
    15             
    16             while left < right {
    17                 if twoSum == nums[left] + nums[right] {
    18                     return target
    19                 } else if twoSum > nums[left] + nums[right] {
    20                     if twoSum - nums[left] - nums[right] < abs(close) {
    21                         close = twoSum - nums[left] - nums[right]
    22                     }
    23                     left += 1
    24                 } else {
    25                     if nums[left] + nums[right] - twoSum < abs(close) {
    26                         close = twoSum - nums[left] - nums[right]
    27                     }
    28                     right -= 1
    29                 }
    30             }
    31             
    32             
    33         }
    34         
    35         return target - close
    36     }
    37 }

    32ms

     1 class Solution {
     2     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     3         guard nums.count > 2 else { return 0 }
     4         
     5         var finalSum = nums[0] + nums[1] + nums[2]
     6         var nums = nums.sorted(){$0 < $1}
     7         for i in 0..<nums.count - 2 {
     8             var j = i + 1, k = nums.count - 1
     9             while j < k {
    10                 var currSum = nums[i] + nums[j] + nums[k] 
    11                 if currSum == target {
    12                     return currSum
    13                 }else {
    14                     if abs(target - currSum) < abs(target - finalSum) {
    15                         finalSum = currSum
    16                     }
    17                     if currSum < target {
    18                         j += 1
    19                     }else {
    20                         k -= 1
    21                     }
    22                 }
    23             }
    24         }
    25         return finalSum
    26     }
    27 }

    36ms

     1 class Solution {
     2     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     3         
     4         var sortedNums = nums.sorted()   
     5         //print(sortedNums)
     6         var closestSum = target >= 0 ? Int.max: Int.min
     7         for index1 in 0..<(nums.count-2) {
     8             var index2 = index1 + 1
     9             var index3 = nums.count - 1
    10             
    11             while (index2 < index3) {
    12                 //print(index1, index2, index3)
    13                 var sum = sortedNums[index1] + sortedNums[index2] + sortedNums[index3]
    14                 if sum == target {
    15                     return sum
    16                 }
    17                 if (abs(target - closestSum) > abs(target - sum)) {
    18                     closestSum = sum
    19                 }
    20 
    21                 //print(closestSum, target)
    22                 if target < sum {
    23                     index3 -= 1
    24                 } else {
    25                     index2 += 1
    26                 }
    27             }
    28         }
    29         return closestSum
    30     }
    31 }

    48ms

     1 class Solution {
     2     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     3         var diff = Int.max
     4         var closestNum = Int.max
     5         let numsSorted = nums.sorted()
     6         let maxIndex = numsSorted.count - 1 
     7         var lastNum: Optional<Int> = nil
     8         for i in 0..<(numsSorted.count - 2) {
     9             let num = numsSorted[i]
    10             if num == lastNum {
    11                 continue
    12             }
    13             
    14             var left = i + 1
    15             var right = maxIndex
    16             let remainder = target - num
    17             while left < right {
    18                 let currentDiff = remainder - numsSorted[left] - numsSorted[right]
    19                 let absCurrentDiff = abs(currentDiff)
    20                 if absCurrentDiff < diff {
    21                     if absCurrentDiff == 0 {
    22                         return target
    23                     }
    24                     diff = absCurrentDiff
    25                     closestNum = target - currentDiff
    26                 }
    27                 
    28                 if currentDiff > 0 {
    29                     left = left + 1
    30                 } else {
    31                     right = right - 1
    32                 }
    33             }
    34             
    35             lastNum = num
    36         }
    37         
    38         return closestNum
    39     }
    40 }

    76ms

     1 class Solution {
     2     var diff = Int.max
     3     var sum = 0
     4     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     5         if nums.count < 3 {
     6             return 0
     7         }
     8         
     9         var nums = nums
    10         nums.sort { $0 < $1 }
    11         print(nums)
    12         
    13         for i in 0..<nums.count-2 {
    14             twoSumClosest(i + 1, nums.count - 1, nums[i], nums, target - nums[i])
    15         }
    16         return sum
    17     }
    18     
    19     func twoSumClosest(_ start: Int, _ end: Int, _ num: Int, _ nums: [Int], _ target: Int) {
    20         var start = start
    21         var end = end
    22         while start < end {
    23             if abs(nums[start] + nums[end] - target) < diff {
    24                 sum = nums[start] + nums[end] + num
    25                 diff = abs(nums[start] + nums[end] - target)
    26             } 
    27             
    28             if nums[start] + nums[end] < target {
    29                 start += 1
    30             }
    31             else {
    32                 end -= 1
    33             }
    34         }
    35     }
    36 }

    96ms

     1 class Solution {
     2     func twoSumClosest(sortedNums: [Int], beginIndex: Int, target: Int) -> Int {
     3         var minGap = Int.max
     4         var closestSum = 0
     5 
     6         var low = beginIndex
     7         var high = sortedNums.count - 1
     8 
     9 
    10         while low < high {
    11             let sum = sortedNums[low] + sortedNums[high]
    12 
    13             // 更新相关结果
    14             let gap = abs(sum - target)
    15             if gap < minGap {
    16                 minGap = gap
    17                 closestSum = sum
    18             }
    19 
    20             // 移动下标
    21             if sum < target {
    22                 repeat {
    23                     low += 1
    24                 } while sortedNums[low] == sortedNums[low - 1] && low < high
    25             } else {
    26                 repeat {
    27                     high -= 1
    28                 } while sortedNums[high] == sortedNums[high + 1] && low < high
    29             }
    30         }
    31 
    32         return closestSum
    33     }
    34 
    35     func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
    36         guard nums.count >= 3 else { return 0 }
    37         var minGap = Int.max
    38         var closestSum = 0
    39 
    40         let sortedNums = nums.sorted()
    41 
    42         for i in 0..<sortedNums.count - 2 {
    43             let closest2Sum = twoSumClosest(sortedNums: sortedNums, beginIndex: i + 1, target: target - sortedNums[i])
    44             let sum = closest2Sum + sortedNums[i]
    45             let gap = abs(target - sum)
    46 
    47             if gap < minGap {
    48                 minGap = gap
    49                 closestSum = sum
    50             }
    51         }
    52 
    53         return closestSum
    54     }
    55 }
  • 相关阅读:
    点分治 / 点分树题目集
    HNOI2019 游记
    WC2019 题目集
    SA / SAM 题目集
    Min_25 筛小结
    NOIP2018 差点退役记
    Atcoder 乱做
    DP及其优化
    计数与概率期望小结
    分库分表之后全局id咋生成?
  • 原文地址:https://www.cnblogs.com/strengthen/p/9885069.html
Copyright © 2011-2022 走看看