forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
house-robber-iv.py
60 lines (55 loc) · 1.43 KB
/
house-robber-iv.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
# Time: O(nlogn)
# Space: O(n)
# binary search, greedy
class Solution(object):
def minCapability(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def check(x):
cnt = i = 0
while i < len(nums):
if nums[i] <= x:
cnt += 1
i += 2
else:
i += 1
return cnt >= k
sorted_nums = sorted(set(nums))
left, right = 0, len(sorted_nums)-1
while left <= right:
mid = left + (right-left)//2
if check(sorted_nums[mid]):
right = mid-1
else:
left = mid+1
return sorted_nums[left]
# Time: O(nlogr)
# Space: O(1)
# binary search, greedy
class Solution2(object):
def minCapability(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def check(x):
cnt = i = 0
while i < len(nums):
if nums[i] <= x:
cnt += 1
i += 2
else:
i += 1
return cnt >= k
left, right = min(nums), max(nums)
while left <= right:
mid = left + (right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left