在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array You need to return the number of important reverse pairs in the given array. Example1: Input: [1,3,2,3,1] Output: 2 Example2: Input: [2,4,3,5,1] Output: 3 Note:
给定一个数组 你需要返回给定数组中的重要翻转对的数量。 示例 1: 输入: [1,3,2,3,1] 输出: 2 示例 2: 输入: [2,4,3,5,1] 输出: 3 注意:
Runtime: 1632 ms
Memory Usage: 20.3 MB
1 class Solution { 2 func reversePairs(_ nums: [Int]) -> Int { 3 var res:Int = 0 4 var copy:[Int] = nums.sorted(by:<) 5 var bit:[Int] = [Int](repeating:0,count:copy.count + 1) 6 for ele in nums 7 { 8 res += search(&bit, index(copy, 2 * ele + 1)) 9 insert(&bit, index(copy, ele)) 10 } 11 return res 12 } 13 14 func index(_ arr:[Int],_ val:Int) -> Int 15 { 16 var l:Int = 0 17 var r:Int = arr.count - 1 18 var m:Int = 0 19 while(l <= r) 20 { 21 m = l + ((r - l) >> 1) 22 if arr[m] >= val 23 { 24 r = m - 1 25 } 26 else 27 { 28 l = m + 1 29 } 30 } 31 return l + 1 32 } 33 34 func search(_ bit:inout [Int],_ i:Int) -> Int 35 { 36 var i = i 37 var sum:Int = 0 38 while(i < bit.count) 39 { 40 sum += bit[i] 41 i += i & -i 42 } 43 return sum 44 } 45 46 func insert(_ bit:inout [Int],_ i:Int) 47 { 48 var i = i 49 while(i > 0) 50 { 51 bit[i] += 1 52 i -= i & -i 53 } 54 } 55 }
|
请发表评论