为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode493. 翻转对 | Reverse Pairs

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10348715.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].

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. 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) 称作一个重要翻转对

你需要返回给定数组中的重要翻转对的数量。

示例 1:

输入: [1,3,2,3,1]
输出: 2

示例 2:

输入: [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 }

 

posted @ 2019-02-02 16:45  为敢技术  阅读(274)  评论(0编辑  收藏  举报