★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-zijewfre-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array nums
, we call (i, j)
an important reverse pair if i < j
and nums[i] > 2*nums[j]
.git
You need to return the number of important reverse pairs in the given array.github
Example1:数组
Input: [1,3,2,3,1] Output: 2
Example2:微信
Input: [2,4,3,5,1] Output: 3
Note:spa
50,000
.给定一个数组 nums
,若是 i < j
且 nums[i] > 2*nums[j]
咱们就将 (i, j)
称做一个重要翻转对。code
你须要返回给定数组中的重要翻转对的数量。htm
示例 1:blog
输入: [1,3,2,3,1] 输出: 2
示例 2:get
输入: [2,4,3,5,1] 输出: 3
注意:
50000
。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 }