-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
peaks-in-array.py
103 lines (90 loc) · 3.14 KB
/
peaks-in-array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# Time: O(n + qlogn)
# Space: O(n)
# bit, fenwick tree
class Solution(object):
def countOfPeaks(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
class BIT(object): # 0-indexed.
def __init__(self, nums):
self.__bit = [0]*(len(nums)+1) # Extra one for dummy node.
for i in xrange(1, len(self.__bit)):
self.__bit[i] = nums[i-1] + self.__bit[i-1]
for i in reversed(xrange(1, len(self.__bit))):
last_i = i - (i & -i)
self.__bit[i] -= self.__bit[last_i]
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = 0
while i > 0:
ret += self.__bit[i]
i -= (i & -i)
return ret
def check(i):
return nums[i-1] < nums[i] > nums[i+1]
def update(x, d):
for i in xrange(max(x-1, 1), min((x+1)+1, len(nums)-1)):
if check(i):
bit.add(i, d)
bit = BIT([int(1 <= i <= len(nums)-2 and check(i)) for i in xrange(len(nums))])
result = []
for t, x, y in queries:
if t == 1:
result.append(bit.query(y-1)-bit.query((x+1)-1) if y-1 >= x+1 else 0)
continue
update(x, -1)
nums[x] = y
update(x, +1)
return result
# Time: O(nlogn + qlogn)
# Space: O(n)
# bit, fenwick tree
class Solution2(object):
def countOfPeaks(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = 0
while i > 0:
ret += self.__bit[i]
i -= (i & -i)
return ret
def check(i):
return nums[i-1] < nums[i] > nums[i+1]
def update(x, d):
for i in xrange(max(x-1, 1), min((x+1)+1, len(nums)-1)):
if check(i):
bit.add(i, d)
bit = BIT(len(nums))
for i in xrange(1, len(nums)-1):
if check(i):
bit.add(i, +1)
result = []
for t, x, y in queries:
if t == 1:
result.append(bit.query(y-1)-bit.query((x+1)-1) if y-1 >= x+1 else 0)
continue
update(x, -1)
nums[x] = y
update(x, +1)
return result