-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathvalid-elements-in-an-array.py
More file actions
45 lines (42 loc) · 1.13 KB
/
valid-elements-in-an-array.py
File metadata and controls
45 lines (42 loc) · 1.13 KB
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
# Time: O(n)
# Space: O(n)
# prefix sum
class Solution(object):
def findValidElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
right = [True]*len(nums)
mx = 0
for i in reversed(xrange(len(nums))):
right[i] = mx < nums[i]
mx = max(mx, nums[i])
result = []
mx = 0
for i in xrange(len(nums)):
left = mx < nums[i]
mx = max(mx, nums[i])
if left or right[i]:
result.append(nums[i])
return result
# Time: O(n)
# Space: O(n)
# prefix sum
class Solution2(object):
def findValidElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left = [True]*len(nums)
mx = 0
for i in xrange(len(nums)):
left[i] = mx < nums[i]
mx = max(mx, nums[i])
right = [True]*len(nums)
mx = 0
for i in reversed(xrange(len(nums))):
right[i] = mx < nums[i]
mx = max(mx, nums[i])
return [nums[i] for i in xrange(len(nums)) if left[i] or right[i]]