Skip to content

Commit 7568868

Browse files
author
wuduhren
committed
updates
1 parent 777337b commit 7568868

4 files changed

+98
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Usually the binary search problem, the hard part is to clear all the edge cases.
3+
What will be the edge case? It will be when the recursive function executed at the deepest level. Usually the list with only one or two element.
4+
So I will suggest before submit, try out the case like [0,1] or [1,0] to make sure it will not run unstop.
5+
"""
6+
class Solution:
7+
def findMin(self, nums: List[int]) -> int:
8+
def helper(l, r):
9+
nonlocal ans
10+
if l>r: return
11+
12+
m = l + int((r-l)/2)
13+
if nums[l]<=nums[m]:
14+
ans = min(ans, nums[l])
15+
helper(m+1, r)
16+
else:
17+
ans = min(ans, nums[m+1])
18+
helper(l, m)
19+
20+
ans = float('inf')
21+
helper(0, len(nums)-1)
22+
return ans
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def minEatingSpeed(self, piles: List[int], h: int) -> int:
3+
def canFinish(k):
4+
timeNeeded = 0
5+
for pile in piles:
6+
timeNeeded += math.ceil(pile/k)
7+
return timeNeeded<=h
8+
9+
kMin = 1
10+
kMax = max(piles)
11+
ans = kMax
12+
13+
while kMin<=kMax:
14+
k = kMin + int((kMax-kMin)/2)
15+
if canFinish(k):
16+
ans = min(ans, k)
17+
kMax = k-1
18+
else:
19+
kMin = k+1
20+
21+
return ans
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def findMedianSortedArrays(self, A: List[int], B: List[int]) -> float:
3+
if len(A)>len(B): A, B = B, A
4+
5+
total = len(A)+len(B)
6+
half = total//2
7+
l = 0
8+
r = len(A)-1
9+
10+
while True:
11+
i = l + (r-l)//2
12+
j = half-(i+1)-1
13+
14+
Aleft = A[i] if i>=0 else float('-inf')
15+
Aright = A[i+1] if i+1<len(A) else float('inf')
16+
Bleft = B[j] if j>=0 else float('-inf')
17+
Bright = B[j+1] if j+1<len(B) else float('inf')
18+
19+
if Aleft<=Bright and Bleft<=Aright:
20+
if total%2==0:
21+
return (max(Aleft, Bleft)+min(Aright, Bright))/2
22+
else:
23+
return min(Aright, Bright)
24+
elif Aleft>Bright:
25+
r = i-1
26+
else:
27+
l = i+1
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class TimeMap:
2+
3+
def __init__(self):
4+
self.data = collections.defaultdict(list)
5+
6+
def set(self, key: str, value: str, timestamp: int) -> None:
7+
self.data[key].append((timestamp, value))
8+
9+
def get(self, key: str, timestamp: int) -> str:
10+
dataList = self.data[key]
11+
l = 0
12+
r = len(dataList)-1
13+
ans = ''
14+
15+
while l<=r:
16+
m = l + int((r-l)/2)
17+
t = dataList[m][0]
18+
19+
if t<timestamp:
20+
ans = dataList[m][1]
21+
l = m+1
22+
elif t>timestamp:
23+
r = m-1
24+
else:
25+
ans = dataList[m][1]
26+
break
27+
28+
return ans

0 commit comments

Comments
 (0)