[Swift]LeetCode16. 最接近的三数之和 | 3Sum Closest

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 }

原文地址:https://www.cnblogs.com/strengthen/p/9885069.html

时间: 2024-10-09 22:30:04

[Swift]LeetCode16. 最接近的三数之和 | 3Sum Closest的相关文章

LeetCode16.最接近的三数之和 JavaScript

给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存在唯一答案. 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 答案参考 /** * @param {number[]} nums * @param {number} target * @return {num

LeetCode:最接近的三数之和【16】

LeetCode:最接近的三数之和[16] 题目描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存在唯一答案. 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 题目分析 这道题就是三数之和问题的一种变形. 三数之和问题的求解策略是将三指针变为双指针问题

两数之和,三数之和,最接近的三数之和,四数之和

LeetCode有一系列做法套路相同的题目,N数之和就可以算一个 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元素. 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 第一个解决办法,简单暴力,堆for循环就是,但

LeetCode OJ:3Sum Closest(最接近的三数之和)

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. For example, given array S = {-1 2

每天AC系列(二):最接近的三数之和

1 题目 leetcode第16题,给定一个数组与一个目标数,找出数组中其中的三个数,这三个数的和要与目标数最接近. 2 暴力 按惯例先来一次O(n3)的暴力: int temp = nums[0]+nums[1]+nums[2]; for(int i=0;i<nums.length;++i) for(int j=i+1;j<nums.length;++j) for(int k=j+1;k<nums.length;++k) { int temp1 = nums[i]+nums[j]+nu

[leetcode 16] 最接近的三数之和

给定一个包括n的整数数组nums,和一个目标值target.找出nums中的三个整数,使得它们的和与target最接近,返回这三个数的和.假定每次输入只存在一个答案. 示例: nums = [-1,2,1,-4] 和 target = 1 与 target 最接近的三个数的和为2. (-1+2+1=2) 代码: class Solution(object): def threeSumClosest(self,nums,target): """ :type nums: List

16.最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存在唯一答案. 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). class Solution {    public int threeSumClosest(int[] nums, int target) { 

16. 最接近的三数之和 O(N^2)

给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存在唯一答案. 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 思路就是先枚举一个数字,然后用尺取确定另外两个数字. class Solution { public: int threeSumClosest(v

6.最接近的三数之和

题目:给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和. 注意事项 只需要返回三元组之和,无需返回三元组本身 class Solution {public:    /**     * @param numbers: Give an array numbers of n integer     * @param target: An integer     * @return: return the sum of the three intege