File tree 1 file changed +60
-0
lines changed
1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(nlogr) = O(n * 30)
2
+ # Space: O(logr) = O(30)
3
+
4
+ # freq table, two pointers
5
+ class Solution (object ):
6
+ def minimumSubarrayLength (self , nums , k ):
7
+ """
8
+ :type nums: List[int]
9
+ :type k: int
10
+ :rtype: int
11
+ """
12
+ def update (x , d , curr ):
13
+ for i in xrange (len (cnt )):
14
+ if x < (1 << i ):
15
+ break
16
+ if not (x & (1 << i )):
17
+ continue
18
+ if cnt [i ] == 0 :
19
+ curr ^= 1 << i
20
+ cnt [i ] += d
21
+ if cnt [i ] == 0 :
22
+ curr ^= 1 << i
23
+ return curr
24
+
25
+ total = reduce (lambda x , y : x | y , nums )
26
+ if total < k :
27
+ return - 1
28
+ cnt = [0 ]* total .bit_length ()
29
+ result = len (nums )
30
+ left = curr = 0
31
+ for right in xrange (len (nums )):
32
+ curr = update (nums [right ], + 1 , curr )
33
+ while left <= right and curr >= k :
34
+ result = min (result , right - left + 1 )
35
+ curr = update (nums [left ], - 1 , curr )
36
+ left += 1
37
+ return result
38
+
39
+
40
+ # Time: O(n^2)
41
+ # Space: O(1)
42
+ # brute force
43
+ class Solution2 (object ):
44
+ def minimumSubarrayLength (self , nums , k ):
45
+ """
46
+ :type nums: List[int]
47
+ :type k: int
48
+ :rtype: int
49
+ """
50
+ result = float ("inf" )
51
+ for left in xrange (len (nums )):
52
+ curr = 0
53
+ for right in xrange (left , len (nums )):
54
+ curr |= nums [right ]
55
+ if curr < k :
56
+ continue
57
+ result = min (result , right - left + 1 )
58
+ break
59
+ return result if result != float ("inf" ) else - 1
60
+
You can’t perform that action at this time.
0 commit comments