在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. Example 1: Input: nums = [1,3,1] k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0. Note:
给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。 示例 1: 输入: nums = [1,3,1] k = 1 输出:0 解释: 所有数对如下: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 因此第 1 个最小距离的数对是 (1,1),它们之间的距离为 0。 提示:
Runtime: 68 ms
Memory Usage: 19.6 MB
1 class Solution { 2 func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int { 3 var nums = nums.sorted(by:<) 4 var n:Int = nums.count 5 var left:Int = 0 6 var right:Int = nums.last! - nums[0] 7 while (left < right) 8 { 9 var mid:Int = left + (right - left) / 2 10 var cnt:Int = 0 11 var start:Int = 0 12 for i in 0..<n 13 { 14 while (start < n && nums[i] - nums[start] > mid) 15 { 16 start += 1 17 } 18 cnt += i - start 19 } 20 if cnt < k 21 { 22 left = mid + 1 23 } 24 else 25 { 26 right = mid 27 } 28 } 29 return right 30 } 31 } 72ms 1 class Solution { 2 func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int { 3 var sorted = nums 4 sorted.sort { $0 < $1 } 5 6 var lo = 0 7 var hi = sorted[sorted.count - 1] - sorted[0] 8 while lo < hi { 9 let m = lo + ((hi - lo) / 2) 10 var count = 0 11 var j = 0 12 for i in 0 ..< sorted.count - 1 { 13 while j < sorted.count && sorted[j] - sorted[i] <= m { 14 j += 1 15 } 16 count += j - i - 1 17 } 18 if count < k { 19 lo = m + 1 20 } else { 21 hi = m 22 } 23 } 24 return lo 25 } 26 } 88ms 1 class Solution { 2 func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int { 3 let nums = nums.sorted() 4 var low = 0, high = abs((nums.first ?? 0) - (nums.last ?? 0)) 5 while low < high { 6 let m = (low + high) / 2 7 var count = 0 8 var j = 1 9 for i in 0..<nums.count-1 { 10 while j < nums.count && nums[j] - nums[i] <= m { j += 1 } 11 count += j-i-1; 12 } 13 if count < k { 14 low = m + 1 15 } else { 16 high = m 17 } 18 } 19 return low 20 } 21 }
|
请发表评论