[Swift]LeetCode493. 翻轉對 | Reverse Pairs

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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

  1. The length of the given array will not exceed 50,000.
  2. All the numbers in the input array are in the range of 32-bit integer.

給定一個數組 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

注意:

  1. 給定數組的長度不會超過50000
  2. 輸入數組中的全部數字都在32位整數的表示範圍內。

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 }
相關文章
相關標籤/搜索