Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Note:
- n is a positive integer, which is in the range of [1, 10000].
- All the integers in the array will be in the range of [-10000, 10000].
给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
示例 1:
输入: [1,4,3,2] 输出: 4 解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).
提示:
- n 是正整数,范围在 [1, 10000].
- 数组中的元素范围在 [-10000, 10000].
128ms
1 class Solution { 2 func arrayPairSum(_ nums: [Int]) -> Int { 3 //升序排序,使每一对的两个数字尽可能接近 4 var arr:[Int] = nums.sorted(by: <) 5 var sum:Int = 0 6 //奇数位置(偶数索引)求和 7 for i in stride(from: 0,to: arr.count,by: 2) 8 { 9 sum += arr[i] 10 } 11 return sum 12 } 13 }
192ms
1 class Solution { 2 func arrayPairSum(_ nums: [Int]) -> Int { 3 var tempSum = 0 4 let sortedArray = nums.sorted(by: <) 5 var tempPair = [Int]() 6 for number in sortedArray { 7 if tempPair.count < 1 { 8 tempPair.append(number) 9 } else { 10 if let min = tempPair.min() { 11 tempSum += min 12 } 13 tempPair.removeAll() 14 } 15 } 16 return tempSum 17 } 18 }
196ms
1 class Solution { 2 func arrayPairSum(_ nums: [Int]) -> Int { 3 var temps = nums 4 quickSort(numbers: &temps, start: 0, end: temps.count - 1) 5 var sum = 0 6 for (index, num) in temps.enumerated() { 7 if index % 2 == 0 { 8 sum = sum + num 9 } 10 } 11 return sum 12 } 13 14 func quickSort(numbers: inout [Int], start: Int, end: Int) { 15 if start > end { 16 return 17 } 18 19 let pivot = partition(numbers: &numbers, start: start, end: end) 20 21 quickSort(numbers: &numbers, start: start, end: pivot - 1) 22 quickSort(numbers: &numbers, start: pivot + 1, end: end) 23 } 24 25 func partition(numbers: inout [Int], start: Int, end: Int) -> Int { 26 let pivot = numbers[start] 27 var left = start 28 var right = end 29 30 var index = start 31 while left <= right { 32 while right >= left { 33 if numbers[right] < pivot { 34 numbers[index] = numbers[right] 35 index = right 36 left = left + 1 37 break 38 } 39 right = right - 1 40 } 41 42 while right >= left { 43 if numbers[left] > pivot { 44 numbers[index] = numbers[left] 45 index = left 46 right = right - 1 47 break 48 } 49 left = left + 1 50 } 51 } 52 53 numbers[index] = pivot 54 return index 55 } 56 }
原文地址:https://www.cnblogs.com/strengthen/p/9842430.html
时间: 2024-10-08 10:41:51