Skip to content

Commit 6f00d18

Browse files
committed
no message
1 parent a9671e8 commit 6f00d18

13 files changed

+280
-2
lines changed

problems/add-strings.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution(object):
2+
def addStrings(self, nums1, nums2):
3+
ans = ''
4+
i = len(nums1)-1
5+
j = len(nums2)-1
6+
7+
carry = 0
8+
while 0<=i and 0<=j:
9+
n1 = int(nums1[i])
10+
n2 = int(nums2[j])
11+
total = n1+n2+carry
12+
n = total%10
13+
carry = 1 if total>=10 else 0
14+
ans = str(n)+ans
15+
i -= 1
16+
j -= 1
17+
18+
while 0<=i:
19+
total = int(nums1[i])+carry
20+
n = total%10
21+
carry = 1 if total>=10 else 0
22+
ans = str(n)+ans
23+
i -= 1
24+
25+
while 0<=j:
26+
total = int(nums2[j])+carry
27+
n = total%10
28+
carry = 1 if total>=10 else 0
29+
ans = str(n)+ans
30+
j -= 1
31+
32+
if carry: ans = str(carry)+ans
33+
34+
return ans

problems/cheapest-flights-within-k-stops.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,19 @@ class Solution1(object):
2323
def findCheapestPrice(self, n, flights, src, dst, K):
2424
graph = collections.defaultdict(list)
2525
pq = []
26+
visited = set()
2627

2728
for u, v, w in flights: graph[u].append((w, v))
2829

2930
heapq.heappush(pq, (0, K+1, src))
3031
while pq:
3132
price, stops, city = heapq.heappop(pq)
33+
visited.add(city)
3234

3335
if city is dst: return price
3436
if stops>0:
3537
for price_to_nei, nei in graph[city]:
38+
if nei in visited: continue
3639
heapq.heappush(pq, (price+price_to_nei, stops-1, nei))
3740
return -1
3841

problems/continuous-subarray-sum.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution(object):
2+
def checkSubarraySum(self, nums, k):
3+
prefixSumEndings = collections.defaultdict(list)
4+
prefixSumEndings[0].append(-1)
5+
6+
prefixSum = 0
7+
for i, n in enumerate(nums):
8+
prefixSum += n
9+
10+
x = prefixSum/k
11+
while x>=0:
12+
p2 = prefixSum-k*x
13+
if len(prefixSumEndings[p2])>0 and prefixSumEndings[p2][0]<i-1:
14+
return True
15+
x -= 1
16+
prefixSumEndings[prefixSum].append(i)
17+
18+
return False
19+
20+
class Solution(object):
21+
def checkSubarraySum(self, nums, k):
22+
if len(nums)==0 or len(nums)==1: return False
23+
prefixSumKRemain = collections.defaultdict(list)
24+
25+
prefixSum = 0
26+
for i, n in enumerate(nums):
27+
prefixSum += n
28+
remain = prefixSum%k
29+
30+
if prefixSum%k==0 and i>=1: return True
31+
if len(prefixSumKRemain[remain])>0 and prefixSumKRemain[remain][0]<i-1:
32+
return True
33+
prefixSumKRemain[remain].append(i)
34+
35+
return False

problems/cutting-ribbons.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution(object):
2+
def maxLength(self, ribbons, k):
3+
maxLen = max(ribbons)
4+
minLen = 0
5+
6+
while minLen<maxLen:
7+
l = minLen + (maxLen-minLen+1)/2
8+
9+
if sum([ribbonLen/l for ribbonLen in ribbons])>=k:
10+
minLen = l
11+
else:
12+
maxLen = l-1
13+
return maxLen
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution(object):
2+
def exclusiveTime(self, n, logs):
3+
ans = [0]*n
4+
data = []
5+
for log in logs:
6+
fid, action, t = log.split(':')
7+
data.append([int(t), -1 if action=='start' else 1, int(fid)])
8+
9+
data.sort()
10+
11+
stack = []
12+
for t, action, fid in data:
13+
if action==-1:
14+
if stack:
15+
prevT, _, prevFid = stack[-1]
16+
ans[prevFid] += t-prevT
17+
elif action==1:
18+
prevT, _, prevFid = stack.pop()
19+
ans[fid] += t+1-prevT
20+
if stack: stack[-1][0] = t+1
21+
22+
if action==-1: stack.append([t, action, fid])
23+
24+
return ans

problems/expression-add-operators.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution(object):
2+
def addOperators(self, num, target):
3+
def dfs(num, curr, i):
4+
if i==len(num):
5+
if eval(curr[1:])==target: ans.append(curr[1:])
6+
return
7+
8+
if curr and curr[-1] in operators:
9+
dfs(num, curr+num[i], i+1)
10+
elif curr and curr[-1]=='0':
11+
dfs(num, curr+'+', i)
12+
dfs(num, curr+'-', i)
13+
dfs(num, curr+'*', i)
14+
else:
15+
dfs(num, curr+'+', i)
16+
dfs(num, curr+'-', i)
17+
dfs(num, curr+'*', i)
18+
dfs(num, curr+num[i], i+1)
19+
20+
operators = set(['+', '-', '*'])
21+
ans = []
22+
dfs(num, '+', 0)
23+
return ans

problems/find-peak-element.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,24 @@ def findPeakElement(self, nums):
5454
return l
5555

5656

57-
57+
58+
"""
59+
[l, r] is the possible range.
60+
Keep decreasing the range unsing binary search until l==r.
61+
Pay attention to
62+
m = l+(r-l+1)/2
63+
Sometimes you need m = l+(r-l)/2 to avoid infinite loop.
64+
"""
65+
class Solution(object):
66+
def findPeakElement(self, nums):
67+
l = 0
68+
r = len(nums)-1
69+
70+
while l<r:
71+
m = l+(r-l+1)/2
72+
if nums[m-1]<nums[m]:
73+
l = m
74+
else:
75+
r = m-1
76+
return l
5877

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution(object):
2+
def removeDuplicates(self, s):
3+
stack = []
4+
i = 0
5+
while i<len(s):
6+
if stack and stack[-1]==s[i]:
7+
stack.pop()
8+
else:
9+
stack.append(s[i])
10+
i += 1
11+
12+
return ''.join(stack)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution(object):
2+
def removeInvalidParentheses(self, s):
3+
def dfs(s, curr, i, count):
4+
if count<0: return
5+
if len(curr)>self.maxLen: return
6+
7+
if i>=len(s):
8+
if len(curr)==self.maxLen and count==0:
9+
self.ans.append(curr)
10+
return
11+
12+
if s[i]!='(' and s[i]!=')':
13+
dfs(s, curr+s[i], i+1, count)
14+
elif not curr or s[i]!=curr[-1]:
15+
dfs(s, curr+s[i], i+1, count + (1 if s[i]=='(' else -1))
16+
dfs(s, curr, i+1, count)
17+
elif s[i]==curr[-1]:
18+
dfs(s, curr+s[i], i+1, count + (1 if s[i]=='(' else -1))
19+
20+
def getMaxLen(s):
21+
openCount = removeCount = 0
22+
for c in s:
23+
if c=='(':
24+
openCount += 1
25+
elif c==')':
26+
openCount -= 1
27+
28+
if openCount<0:
29+
removeCount += abs(openCount)
30+
openCount = 0
31+
removeCount += openCount
32+
return len(s)-removeCount
33+
34+
self.ans = []
35+
self.maxLen = getMaxLen(s)
36+
37+
dfs(s, "", 0, 0)
38+
return self.ans
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution(object):
2+
def shortestDistance(self, grid):
3+
def bfs(i0, j0):
4+
q = collections.deque([(i0, j0, 0)])
5+
visited = set()
6+
while q:
7+
i, j, dis = q.popleft()
8+
if (i, j) in visited: continue
9+
visited.add((i, j))
10+
11+
reach[i][j] += 1
12+
distances[i][j] += dis
13+
14+
for iNext, jNext in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)):
15+
if not (0<=iNext<len(grid) and 0<=jNext<len(grid[0])): continue
16+
if grid[iNext][jNext]==2 or grid[iNext][jNext]==1: continue
17+
if (iNext, jNext) in visited: continue
18+
q.append((iNext, jNext, dis+1))
19+
20+
M = len(grid)
21+
N = len(grid[0])
22+
ans = float('inf')
23+
reach = [[0]*N for _ in xrange(M)] #number of buildings can reach (i, j)
24+
distances = [[0]*N for _ in xrange(M)] #aggregate distance btwn 0 and buildings.
25+
buildingCount = 0
26+
27+
for i in xrange(M):
28+
for j in xrange(N):
29+
if grid[i][j]==1:
30+
buildingCount += 1
31+
bfs(i, j)
32+
33+
34+
for i in xrange(M):
35+
for j in xrange(N):
36+
if grid[i][j]==0 and reach[i][j]==buildingCount:
37+
ans = min(ans, distances[i][j])
38+
39+
return ans if ans!=float('inf') else -1
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution(object):
2+
def shortestPathBinaryMatrix(self, grid):
3+
q = collections.deque([(0, 0, 1)])
4+
seen = 2
5+
6+
while q:
7+
i, j, step = q.popleft()
8+
if not (0<=i<len(grid) and 0<=j<len(grid[0])): continue
9+
if grid[i][j]==1 or grid[i][j]==seen: continue
10+
grid[i][j] = seen
11+
12+
if i==len(grid)-1 and j==len(grid[0])-1: return step
13+
14+
for k, l in ((i+1, j), (i-1, j), (i, j+1), (i, j-1), (i-1, j-1), (i+1, j-1), (i+1, j+1), (i-1, j+1)):
15+
q.append((k, l, step+1))
16+
17+
return -1

problems/subarray-sum-equals-k.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ def subarraySum(self, nums, k):
3939
"""
4040
class Solution(object):
4141
def subarraySum(self, nums, k):
42-
N = len(nums)
4342
ans = 0
4443

4544
prefixSumCount = collections.Counter()

problems/toeplitz-matrix.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution(object):
2+
def isToeplitzMatrix(self, matrix):
3+
def check(i0, j0, matrix):
4+
i = i0
5+
j = j0
6+
7+
while 0<=i<len(matrix) and 0<=j<len(matrix[0]):
8+
if matrix[i][j]!=matrix[i0][j0]: return False
9+
i += 1
10+
j += 1
11+
return True
12+
13+
M = len(matrix)
14+
N = len(matrix[0])
15+
16+
for i in xrange(M-1, 0, -1):
17+
if not check(i, 0, matrix): return False
18+
19+
for j in xrange(N):
20+
if not check(0, j, matrix): return False
21+
22+
return True

0 commit comments

Comments
 (0)