在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of distinct integers
Example 1: Input: arr = [4,2,1,3] Output: [[1,2],[2,3],[3,4]] Example 2: Input: arr = [1,3,6,10,15] Output: [[1,3]] Example 3: Input: arr = [3,8,-10,23,19,-4,-14,27] Output: [[-14,-10],[19,23],[23,27]]
Constraints:
给你个整数数组 请你找到所有具有最小绝对差的元素对,并且按升序的顺序返回。
示例 1: 输入:arr = [4,2,1,3] 输出:[[1,2],[2,3],[3,4]] 示例 2: 输入:arr = [1,3,6,10,15] 输出:[[1,3]] 示例 3: 输入:arr = [3,8,-10,23,19,-4,-14,27] 输出:[[-14,-10],[19,23],[23,27]]
提示:
740ms
1 class Solution { 2 func minimumAbsDifference(_ arr: [Int]) -> [[Int]] { 3 let sortArr = arr.sorted() 4 var minDifference = Int.max; 5 var last = 0; 6 var res = [[Int]]() 7 for i in 0..<sortArr.count { 8 if i == 0 { 9 last = sortArr[0] 10 continue 11 } 12 13 let difference = sortArr[i] - last 14 if difference == minDifference { 15 res.append([last, sortArr[i]]) 16 } else if difference < minDifference { 17 res.removeAll() 18 minDifference = sortArr[i] - last; 19 res.append([last, sortArr[i]]) 20 } else { 21 22 } 23 last = sortArr[i] 24 } 25 return res 26 } 27 } 744ms 1 class Solution { 2 func minimumAbsDifference(_ arr: [Int]) -> [[Int]] { 3 let sArr = arr.sorted() 4 5 var minDiff = Int.max 6 var ans: [[Int]] = [] 7 for i in 1 ..< sArr.count { 8 let aDiff = abs(sArr[i] - sArr[i-1]) 9 if aDiff <= minDiff { 10 if aDiff < minDiff { 11 minDiff = aDiff 12 ans.removeAll() 13 } 14 ans.append([sArr[i-1], sArr[i]]) 15 } 16 } 17 18 return ans 19 } 20 } Runtime: 764 ms Memory Usage: 25.1 MB
1 class Solution { 2 func minimumAbsDifference(_ arr: [Int]) -> [[Int]] { 3 var arr = arr 4 arr.sort() 5 let n:Int = arr.count 6 var min_diff:Int = 1_000_000_000 7 var ans:[[Int]] = [[Int]]() 8 for i in 0..<(n-1) 9 { 10 min_diff = min(min_diff, arr[i + 1] - arr[i]) 11 } 12 for i in 0..<(n-1) 13 { 14 if arr[i + 1] - arr[i] == min_diff 15 { 16 ans.append([arr[i], arr[i + 1]]) 17 } 18 } 19 return ans 20 } 21 }
|
请发表评论