Skip to content

Commit 6c06ae2

Browse files
author
weiy
committed
reverse pairs hard
1 parent 42a3808 commit 6c06ae2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

DP/ReversePairs.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
3+
4+
You need to return the number of important reverse pairs in the given array.
5+
6+
Example1:
7+
8+
Input: [1,3,2,3,1]
9+
Output: 2
10+
Example2:
11+
12+
Input: [2,4,3,5,1]
13+
Output: 3
14+
Note:
15+
1. The length of the given array will not exceed 50,000.
16+
2. All the numbers in the input array are in the range of 32-bit integer.
17+
18+
如果索引 i < j 并且 nums[i] > 2 * nums[j],那么就称它为牛波翻转对。
19+
20+
给一个数组,返回里面有几个牛波翻转对。
21+
22+
思路:
23+
24+
一个 Dp 思路,从后向前,解出每一个点若要达成牛波翻转对所需要的值是多少。
25+
26+
比如 1 , 要达成需要 2 以上。
27+
3, 则需要 6 以上。
28+
29+
将这些放到一个列表里,然后来新值之后判断若将它插入这个列表的话所插入的位置(下标),
30+
这个位置即为已经判断过的能与它达成牛波翻转对的位置。
31+
32+
用二分法可以达成 n log n 的查询,美中不足的是列表的插入仍需要 O(n)。
33+
34+
beat 17%
35+
36+
测试地址:
37+
https://leetcode.com/problems/reverse-pairs/description/
38+
39+
40+
"""
41+
import bisect
42+
43+
class Solution(object):
44+
def reversePairs(self, nums):
45+
"""
46+
:type nums: List[int]
47+
:rtype: int
48+
"""
49+
_base = []
50+
51+
result = 0
52+
53+
for i in range(len(nums)-1,-1,-1):
54+
index = bisect.bisect_left(_base, nums[i])
55+
result += index
56+
bisect.insort_right(_base, nums[i]*2)
57+
58+
return result
59+

0 commit comments

Comments
 (0)