1
+ """
2
+ We have some permutation A of [0, 1, ..., N - 1], where N is the length of A.
3
+
4
+ The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].
5
+
6
+ The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].
7
+
8
+ Return true if and only if the number of global inversions is equal to the number of local inversions.
9
+
10
+ Example 1:
11
+
12
+ Input: A = [1,0,2]
13
+ Output: true
14
+ Explanation: There is 1 global inversion, and 1 local inversion.
15
+ Example 2:
16
+
17
+ Input: A = [1,2,0]
18
+ Output: false
19
+ Explanation: There are 2 global inversions, and 1 local inversion.
20
+ Note:
21
+
22
+ A will be a permutation of [0, 1, ..., A.length - 1].
23
+ A will have length in range [1, 5000].
24
+ The time limit for this problem has been reduced.
25
+
26
+ 思路:
27
+ 二分法。
28
+
29
+ 测试地址:
30
+ https://leetcode.com/contest/weekly-contest-69/problems/global-and-local-inversions/
31
+
32
+ """
33
+ import bisect
34
+
35
+ class Solution (object ):
36
+ def isIdealPermutation (self , A ):
37
+ """
38
+ :type A: List[int]
39
+ :rtype: bool
40
+ """
41
+ global_inversions = []
42
+ _g = 0
43
+
44
+ for i in A [::- 1 ]:
45
+ _g += bisect .bisect_left (global_inversions , i )
46
+ bisect .insort_left (global_inversions , i )
47
+
48
+ _l = 0
49
+
50
+ for i in range (len (A )- 1 ):
51
+ if A [i ] > A [i + 1 ]:
52
+ _l += 1
53
+
54
+ return _g == _l
55
+
0 commit comments