File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(nlogn)
2
+ # Space: O(n)
3
+
4
+ class BIT (object ): # 0-indexed.
5
+ def __init__ (self , n ):
6
+ self .__bit = [0 ]* (n + 1 ) # Extra one for dummy node.
7
+
8
+ def add (self , i , val ):
9
+ i += 1 # Extra one for dummy node.
10
+ while i < len (self .__bit ):
11
+ self .__bit [i ] += val
12
+ i += (i & - i )
13
+
14
+ def query (self , i ):
15
+ i += 1 # Extra one for dummy node.
16
+ ret = 0
17
+ while i > 0 :
18
+ ret += self .__bit [i ]
19
+ i -= (i & - i )
20
+ return ret
21
+
22
+
23
+ # bit, fenwick tree, combinatorics
24
+ class Solution (object ):
25
+ def goodTriplets (self , nums1 , nums2 ):
26
+ """
27
+ :type nums1: List[int]
28
+ :type nums2: List[int]
29
+ :rtype: int
30
+ """
31
+ lookup = [0 ]* len (nums1 )
32
+ for i , x in enumerate (nums1 ):
33
+ lookup [x ] = i
34
+ result = 0
35
+ bit = BIT (len (nums1 ))
36
+ for i , x in enumerate (nums2 ):
37
+ smaller = bit .query (lookup [x ]- 1 )
38
+ larger = (len (nums1 )- (lookup [x ]+ 1 ))- (i - smaller )
39
+ result += smaller * larger
40
+ bit .add (lookup [x ], 1 )
41
+ return result
You can’t perform that action at this time.
0 commit comments