在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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:
给定长度为 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). 提示:
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 }
|
请发表评论