Compare commits

...

23 Commits

Author SHA1 Message Date
e95027872a super easy dfs 2024-06-19 23:59:30 +02:00
045676e191 399 graph theory but very funny 2024-06-19 23:49:54 +02:00
c944caec2e 138 copy a list 2024-06-17 23:29:51 +02:00
ed633c85b7 92 list not diffcult 2024-06-16 16:21:09 +02:00
70b05fe146 150 stack 2024-06-16 10:54:21 +02:00
321b2a8668 452 greedy 2024-06-16 10:38:56 +02:00
3a982c9b0c 427 dfs 2024-06-11 15:06:26 +02:00
130ac22f05 easy backtrack 2024-06-10 17:55:46 +02:00
3a451165d6 54 array ops 2024-06-08 17:13:50 +02:00
0f2f3b67d2 155 stack 2024-06-06 21:03:33 +02:00
9087e2a0fe 155 stack 2024-06-06 21:02:52 +02:00
3184bf511e 57 think less and code more... 2024-06-05 23:14:39 +02:00
331fc02f5f 30 not hard but think hard 2024-06-05 16:58:36 +02:00
9ca72f3125 3 need thinking more 2024-06-04 21:20:55 +02:00
Hanzhang ma
0e82709984 array and dic 2024-06-04 15:58:37 +02:00
Hanzhang ma
d819c04697 binary search 2024-06-04 15:58:21 +02:00
886879c4d7 Merge branch 'master' of http://ff.mhrooz.xyz:3000/iicd/leetcode 2024-06-03 17:50:52 +02:00
bccc78b194 2*dp 2*bit 2024-06-03 17:50:37 +02:00
Hanzhang ma
3006568678 a 2024-06-02 21:36:19 +02:00
cdb6cccb89 easy nie 2024-06-02 21:25:22 +02:00
40a4785d66 not understand the code 2024-06-02 21:24:18 +02:00
641f712a20 pass 211 77 433 2024-06-02 21:23:00 +02:00
75690d88f7 433 bfs 2024-06-02 17:57:21 +02:00
29 changed files with 933 additions and 1 deletions

BIN
.DS_Store vendored

Binary file not shown.

63
130-240602-pass/main.py Normal file
View File

@@ -0,0 +1,63 @@
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
que = []
front = -1
tail = -1
def push_back(que, front, tail, ele):
lq = len(que)
tail += 1
if lq <= tail:
que.append(ele)
else:
que[tail] = ele
return tail
def pop(que, front, tail):
front += 1
return (que[front], front)
d = [(1,0),(-1,0),(0,1),(0,-1)]
height = len(board)
width = len(board[0])
def is_valid(x, y):
if x<0 or y < 0 or x >= height or y >= width:
return False
return True
is_visited = []
for x, l in enumerate(board):
is_visited.append([])
for y in l:
is_visited[x].append(0)
if height < 3 or width < 3:
return board
def is_edge(x, y):
if x == 0 or y == 0 or x == height - 1 or y == width - 1:
return True
return False
for x in range(1,height - 1):
for y in range(1,width - 1):
if board[x][y] == 'X' or is_visited[x][y] == 1: continue
tail = push_back(que,front, tail,(x,y))
flag = 0
last_front = front
while front != tail:
(top_ele, front) = pop(que, front, tail)
for (cx, cy) in d:
nx = cx + top_ele[0]
ny = cy + top_ele[1]
if is_edge(nx, ny):
if board[nx][ny] == 'O':
flag = 1
continue
if board[nx][ny] == 'O' and is_visited[nx][ny]==0:
tail = push_back(que,front,tail,(nx,ny))
is_visited[nx][ny]=1
if flag == 0:
for idx in range(last_front + 1, front + 1):
xx = que[idx][0]
yy = que[idx][1]
board[xx][yy]='X'
return board

Binary file not shown.

48
138-240617-pass/main.py Normal file
View File

@@ -0,0 +1,48 @@
class Solution:
def copy RandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
l = []
cur = head
while cur != None:
l.append(cur)
cur = cur.next
n_l = []
for i in range(len(l)):
tmp = Node()
tmp.val = l[i].val
n_l.append(tmp)
for i in range(len(l)):
if l[i].random == None: continue
n_l[i].random = n_l[l[i].random.val]
if i == len(l) - 1: continue
n_l[i].next = n_l[i+1]
return n_l[0]
"""
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if head == None:
return None
l = []
cur = head
cnt = 0
m = {}
while cur != None:
l.append(cur)
m[cur] = cnt
cur = cur.next
cnt += 1
n_l = []
for i in range(len(l)):
tmp = Node(l[i].val)
n_l.append(tmp)
for i in range(len(l)):
if i != len(l) - 1: n_l[i].next = n_l[i+1]
if l[i].random == None: continue
n_l[i].random = n_l[m[l[i].random]]
return n_l[0]

0
150-240616-pass/main.py Normal file
View File

43
155-240605-pass/main.py Normal file
View File

@@ -0,0 +1,43 @@
class MinStack:
def __init__(self):
self.sta = []
self.minn = 2 ** 31
self.tops = -1
self.sorted = []
def push(self, val: int) -> None:
self.tops += 1
if len(self.sta) <= self.tops:
self.sta.append(val)
else:
self.sta[self.tops] = val
flag = False
for ind, num in enumerate(self.sorted):
if val < num:
self.sorted.insert(ind,val)
flag = True
break
if flag == False:
self.sorted.append(val)
self.minn = min(self.minn, val)
def pop(self) -> None:
val = self.sta[self.tops]
self.sorted.remove(val)
self.tops -= 1
def top(self) -> int:
return self.sta[self.tops]
def getMin(self) -> int:
return self.sorted[0]
mins = MinStack()
mins.push(-2)
mins.push(0)
mins.push(-3)
print(mins.getMin())
print(mins.pop())
print(mins.top())
print(mins.getMin())

43
155-240605/main.py Normal file
View File

@@ -0,0 +1,43 @@
class MinStack:
def __init__(self):
self.sta = []
self.minn = 2 ** 31
self.tops = -1
self.sorted = []
def push(self, val: int) -> None:
self.tops += 1
if len(self.sta) <= self.tops:
self.sta.append(val)
else:
self.sta[self.tops] = val
flag = False
for ind, num in enumerate(self.sorted):
if val < num:
self.sorted.insert(ind,val)
flag = True
break
if flag == False:
self.sorted.append(val)
self.minn = min(self.minn, val)
def pop(self) -> None:
val = self.sta[self.tops]
self.sorted.remove(val)
self.tops -= 1
def top(self) -> int:
return self.sta[self.tops]
def getMin(self) -> int:
return self.sorted[0]
mins = MinStack()
mins.push(-2)
mins.push(0)
mins.push(-3)
print(mins.getMin())
print(mins.pop())
print(mins.top())
print(mins.getMin())

19
167-240604-pass/main.py Normal file
View File

@@ -0,0 +1,19 @@
class Solution:
def twoSum(self, numbers: list[int], target: int) -> list[int]:
for idx, num in enumerate(numbers):
finding = target - num
left = idx
right = len(numbers) - 1
while left <= right:
mid = (left + right) // 2
if numbers[mid] == finding:
return [idx + 1, mid + 1]
if numbers[mid] > finding:
right = mid - 1
continue
if numbers[mid] < finding:
left = mid + 1
sol = Solution()
print(sol.twoSum([2, 7 ,11, 15], 26))
print(sol.twoSum([-1, 9], 8))
print(sol.twoSum([2,3,4], 6))

20
190-240603-pass/main.py Normal file
View File

@@ -0,0 +1,20 @@
class Solution:
def reverseBits(self, n: int) -> int:
num = n
l = []
while num != 0:
l.append(num % 2)
num //= 2
rlt = 0
length = len(l)
while len(l) < 32:
l.append(0)
print(l)
l.reverse()
for i, n in enumerate(l):
rlt += n * pow(2, i)
return rlt
sol = Solution()
print(sol.reverseBits(43261596))

16
198-240603-pass/main.py Normal file
View File

@@ -0,0 +1,16 @@
class Solution:
def rob(self, nums: list[int]) -> int:
s = []
rlt = -1e6
for i, num in enumerate(nums):
maxi = num
for j in range(0, i - 1, 1):
maxi = max(s[j] + num, maxi)
s.append(maxi)
rlt = max(maxi, rlt)
return rlt
sol = Solution()
print(sol.rob([1, 2, 3, 1]))
print(sol.rob([2, 7, 9, 3, 1]))
print(sol.rob([2, 7, 9, 9, 3, 1]))

71
211-240602-pass/main.py Normal file
View File

@@ -0,0 +1,71 @@
class TrieNode:
def __init__(self, val = ''):
self.child = []
self.is_word = False
self.val = val
self.child_map = {}
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
parent_node = self.root
for idx, letter in enumerate(word):
if letter not in parent_node.child_map:
new_node = TrieNode(letter)
parent_node.child.append(new_node)
parent_node.child_map[letter] = len(parent_node.child) - 1
parent_node = new_node
else:
idx = parent_node.child_map[letter]
parent_node = parent_node.child[idx]
parent_node.is_word = True
def search(self, word: str) -> bool:
def subsearch(node, word) -> bool:
parent_node = node
if len(word) == 0:
return parent_node.is_word
ch = word[0]
rlt = False
if ch == '.':
flag = 0
for child in parent_node.child_map:
idx = parent_node.child_map[child]
r = subsearch(parent_node.child[idx], word[1:])
if r == True: flag = 1
if flag == 1:
return True
else:
return False
else:
if ch not in parent_node.child_map:
return False
else:
idx = parent_node.child_map[ch]
return subsearch(parent_node.child[idx], word[1:])
return subsearch(self.root, word)
def startsWith(self, prefix: str) -> bool:
parent_node = self.root
for idx, letter in enumerate(prefix):
if letter not in parent_node.child_map:
return False
idx = parent_node.child_map[letter]
parent_node = parent_node.child[idx]
return True
class WordDictionary:
def __init__(self):
self.tree = Trie()
def addWord(self, word: str) -> None:
self.tree.insert(word)
def search(self, word: str) -> bool:
return self.tree.search(word)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

10
26-240604-pass/main.py Normal file
View File

@@ -0,0 +1,10 @@
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
k = {}
cnt = 0
for num in nums:
if num not in k:
nums[cnt] = num
cnt += 1
k[num] = 1
return cnt

36
3-240603-pass/main.py Normal file
View File

@@ -0,0 +1,36 @@
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic = {}
def encode(ch) -> int:
if ch not in dic:
dic[ch] = len(dic)
return dic[ch]
l = [0 for i in range(108)]
rlt = 0
start = 0
for i, ch in enumerate(s):
idx = encode(ch)
if(l[idx] >= 1):
rlt = max(rlt, i - start )
# print("now", start, rlt)
while start < i and l[idx] >= 1:
tmp = encode(s[start])
start = start + 1
l[tmp] -= 1
l[idx] += 1
# print(ch, start, l )
rlt = max(rlt, len(s) - start )
if rlt == 0: return len(s)
return rlt
sol = Solution()
print(sol.lengthOfLongestSubstring("abcabcbb"))
print(sol.lengthOfLongestSubstring("bbbbb"))
print(sol.lengthOfLongestSubstring("pwwkew"))
print(sol.lengthOfLongestSubstring("abcde"))
print(sol.lengthOfLongestSubstring("abcdbej"))
print(sol.lengthOfLongestSubstring("bbcdjeb"))
print(sol.lengthOfLongestSubstring(" "))
print(sol.lengthOfLongestSubstring("1 b 234aac 2"))

146
30-240604/main.py Normal file
View File

@@ -0,0 +1,146 @@
class TrieNode:
def __init__(self, val = ''):
self.child = []
self.is_word = 0
self.val = val
self.t = 1
self.child_map = {}
class Trie:
def __init__(self):
self.root = TrieNode()
self.cnt = 0
def insert(self, word: str) -> None:
parent_node = self.root
for idx, letter in enumerate(word):
if letter not in parent_node.child_map:
new_node = TrieNode(letter)
parent_node.child.append(new_node)
parent_node.child_map[letter] = len(parent_node.child) - 1
parent_node = new_node
else:
idx = parent_node.child_map[letter]
parent_node = parent_node.child[idx]
if parent_node.is_word != 0:
parent_node.t += 1
parent_node.is_word = self.cnt + 1
self.cnt += 1
def search(self, word: str) :
parent_node = self.root
for idx, letter in enumerate(word):
if letter not in parent_node.child_map:
return None
idx = parent_node.child_map[letter]
parent_node = parent_node.child[idx]
if parent_node.is_word != 0:
return parent_node
return None
def startsWith(self, prefix: str) -> bool:
parent_node = self.root
for idx, letter in enumerate(prefix):
if letter not in parent_node.child_map:
return False
idx = parent_node.child_map[letter]
parent_node = parent_node.child[idx]
return True
class Solution:
def findSubstring(self, s: str, words: list[str]) -> list[int]:
len_word = len(words[0])
tree = Trie()
is_word = []
rlt = []
state = []
word_cnt = {}
if len_word > len(s): return []
for word in words:
tree.insert(word)
r = tree.search(word)
if r != None:
word_cnt[r.is_word] = r.t
# print(word_cnt)
for idx, ch in enumerate(s):
if idx + len_word > len(s): break
waiting = s[idx:idx+len_word]
r = tree.search(waiting)
if r != None:
is_word.append(r.is_word)
else:
is_word.append(0)
for i in range(len_word - 1) : is_word.append(0)
for i in range(len_word):
if is_word[i] != 0:
tmp_dic = {is_word[i]: [i]}
state.append((tmp_dic,i,i))
else:
state.append(({},i,i))
if len(words) == 1 and words[0] == s:
return [0]
# is_word[idx] = value words index / 0 if it is not a word
# state[dic_idx][0]
for i in range(len(is_word[len_word:])):
idx = i + len_word
dic_idx = idx % len_word
# print(f"current index: {idx}, {idx % len_word}")
# print(f"current dic: {state[dic_idx]}")
# print(f"is_word[idx]: {is_word[idx]}")
if is_word[idx] in state[dic_idx][0] and len(state[dic_idx][0][is_word[idx]]) >= word_cnt[is_word[idx]]:
# print("condition 1")
tmp = state[dic_idx][0][is_word[idx]][0]
tmp_l = []
for key in state[dic_idx][0]:
for i, v in enumerate(state[dic_idx][0][key]):
if v <= tmp:
tmp_l.append((key, i))
for (key, i) in tmp_l:
state[dic_idx][0][key].pop(i)
if len(state[dic_idx][0][key]) == 0:
del state[dic_idx][0][key]
if is_word[idx] not in state[dic_idx][0]:
state[dic_idx][0][is_word[idx]] = [idx]
else:
state[dic_idx][0][is_word[idx]].append(idx)
state[dic_idx] = (state[dic_idx][0], tmp + len_word, state[dic_idx][2])
elif is_word[idx] != 0:
# print("condition 2")
if len(state[dic_idx][0]) == 0:
state[dic_idx] = ({}, idx, idx)
if is_word[idx] in state[dic_idx][0]:
state[dic_idx][0][is_word[idx]].append(idx)
else:
state[dic_idx][0][is_word[idx]]=[idx]
elif is_word[idx] == 0:
# print("condition 3")
state[dic_idx] = ({}, idx, idx)
state[dic_idx] = (state[dic_idx][0],state[dic_idx][1], idx)
s = 0
for k in state[dic_idx][0]:
s += len(state[dic_idx][0][k])
# if len(state[dic_idx][0]) == len(words):
if s == len(words):
# print(f"win, {idx}")
rlt.append(state[dic_idx][1])
del state[dic_idx][0][is_word[state[dic_idx][1]]]
state[dic_idx] = (state[dic_idx][0], state[dic_idx][1] + len_word, state[dic_idx][2])
# print(f"after fixed: {state[dic_idx]}")
# print()
return rlt
sol = Solution()
print(sol.findSubstring("barfoothefoobarman", words=["foo", "bar"]))
print(sol.findSubstring("barfoofoobarthefoobarman", words=["foo", "bar", "the"]))
print(sol.findSubstring("barbarbbar", words=["arb", "bar"]))
print(sol.findSubstring("wordgoodgoodgoodbestword", words=["word", "good", "good", "best"]))
print(sol.findSubstring("aaa", words=["a"]))
print(sol.findSubstring("word", words=["word"]))

16
39-240619-pass/main.py Normal file
View File

@@ -0,0 +1,16 @@
class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
candidates.sort()
rlt = []
def dfs(cur, l, cur_num):
if cur == 0:
rlt.append(l)
for candidate in candidates:
if cur - candidate >= 0 and candidate >= cur_num:
dfs(cur - candidate, l + [candidate], candidate)
dfs(target, [], candidates[0])
return rlt
sol = Solution()
print(sol.combinationSum([2,3,6,7], 7))

View File

@@ -7,7 +7,6 @@ class Solution:
if cht == chs:
idt_m = idt + idt_m + 1
cnt += 1
print(idt_m, idt, cht)
break
if cnt == len(s): return True
return False

55
399-240619-pass/main.py Normal file
View File

@@ -0,0 +1,55 @@
class Solution:
def calcEquation(self, equations: list[list[str]], values: list[float], queries: list[list[str]]) -> list[float]:
vs = []
for equation in equations:
first_var = equation[0]
second_var = equation[1]
if first_var not in vs:
vs.append(first_var)
if second_var not in vs:
vs.append(second_var)
index_map = {}
for ind, var in enumerate(vs):
index_map[var] = ind
ls = []
vs_len = len(vs)
for ind, var in enumerate(vs):
ls.append([])
for i in range(vs_len):
if i == ind:
ls[ind].append(1)
else:
ls[ind].append(-1)
for ind, equation in enumerate(equations):
first_ind = index_map[equation[0]]
second_ind = index_map[equation[1]]
ls[first_ind][second_ind] = values[ind]
ls[second_ind][first_ind] = 1.0 / values[ind]
flag = 1
while flag == 1:
flag = 0
for i in range(vs_len):
for j in range(vs_len):
for k in range(vs_len):
if ls[i][j] != -1 : continue
if ls[i][k] == -1 or ls[k][j] == -1: continue
flag = 1
ls[i][j] = ls[i][k] * ls[k][j]
ls[j][i] = 1.0/ls[i][j]
output = []
for query in queries:
if query[0] not in vs or query[1] not in vs:
output.append(-1)
continue
first_ind = index_map[query[0]]
second_ind = index_map[query[1]]
output.append(ls[first_ind][second_ind])
return output
sol = Solution()
print(sol.calcEquation([["a", "b"], ["b", "c"]], [2.0, 3.0], [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]))
print(sol.calcEquation([["a", "c"], ["b", "e"],["c", "d"], ["e", "d"]], [2.0, 3.0,0.5,5.0], [["a", "b"]]))

41
427-240611-pass/main.py Normal file
View File

@@ -0,0 +1,41 @@
"""
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
"""
class Solution:
def construct(self, grid: List[List[int]]) -> 'Node':
n = len(grid)
def check_is_leaf(row_start,row_end,column_start,column_end):
x = grid[row_start][column_start]
for i in range(row_start, row_end + 1):
for j in range(column_start, column_end + 1):
if grid[i][j] != x:
return 0
return 1
def dfs(dim, row, column,node):
isLeaf = check_is_leaf(row,row+dim -1 , column, column + dim - 1)
node.isLeaf= isLeaf
if isLeaf==1:
node.val=grid[row][column]
else:
node.val = 1
top_left = Node()
node.topLeft = dfs(dim // 2, row, column, top_left)
top_right = Node()
node.topRight = dfs(dim // 2, row, column + dim // 2, top_right)
bottom_left = Node()
node.bottomLeft = dfs(dim // 2, row + dim // 2, column, bottom_left)
bottom_right = Node()
node.bottomRight = dfs(dim // 2, row + dim // 2, column + dim // 2, bottom_right)
return node
root = Node()
root = dfs(n,0,0,root)
return root

38
433-240602-pass/main.py Normal file
View File

@@ -0,0 +1,38 @@
class Solution:
def minMutation(self, startGene: str, endGene: str, bank: list[str]) -> int:
if endGene not in bank: return -1
que = []
front = -1
tail = -1
def push_back(que, front, tail, ele):
tail += 1
if tail >= len(que):
que.append(ele)
else:
que[tail] = ele
return tail
def pop(que, front ,tail):
front += 1
return (front , que[front])
tail = push_back(que,front,tail,(startGene,0))
def diff(str1, str2) -> int:
rlt = 0
for idx, ch in enumerate(str1):
if(str1[idx] != str2[idx]): rlt += 1
return rlt
rlt = 1e5
while front != tail:
(front, top_ele) = pop(que, front, tail)
step = top_ele[1]
string = top_ele[0]
if diff(string, endGene) == 0: return step
for s in bank:
diff_num = diff(s, string)
# print(diff_num)
if diff_num == 1:
tail = push_back(que, front, tail, (s, step + 1))
return -1
sol = Solution()
print(sol.minMutation("AACCGGTT","AACCGGTA",["AACCGGTA"]))
print(sol.minMutation("AACCGGTT","AAACGGTA",["AACCGGTA","AACCGCTA","AAACGGTA"]))

18
452-240616-pass/main.py Normal file
View File

@@ -0,0 +1,18 @@
class Solution:
def findMinArrowShots(self, points: list[list[int]]) -> int:
def rule(l):
return (l[0], l[1])
sorted_points = sorted(points, key=rule)
rlt = 0
end = -inf
for point in sorted_points:
st = point[0]
ed = point[1]
if st > end:
rlt += 1
end = ed
else:
end = min(end, ed)
return rlt
sol = Solution()
print(sol.findMinArrowShots([[10, 16],[2, 8],[1, 6], [7, 12]]))

26
46-240610-pass/main.py Normal file
View File

@@ -0,0 +1,26 @@
class Solution:
def permute(self,nums: list[int]) -> list[list[int]]:
length = len(nums)
l = [i for i in range(length)]
permute = []
s = set()
def get_permute(l, num, length, s, cur):
if num == length:
permute.append(cur)
return
for i in range(length):
if i not in s:
s.add(i)
cur.append(i)
get_permute(l, num+1, length, s, cur.copy())
cur.pop()
s.remove(i)
get_permute(l,0,length, s, cur=[])
rlt = []
for li in permute:
rlt.append([nums[i] for i in li])
return rlt
sol = Solution()
print(sol.permute([1, 2, 3]))

32
54-240608-pass/main.py Normal file
View File

@@ -0,0 +1,32 @@
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
d = [(0,1),(1,0),(0,-1),(-1,0)]
cur_d = 0
width = len(matrix[0])
height = len(matrix)
m, n = width, height - 1
cur_m, cur_n = 0,0
cur_p = (0,0)
rlt = []
for i in range(width * height):
# print(cur_p, m, n, cur_m, cur_n)
row = cur_p[0]
col = cur_p[1]
rlt.append(matrix[row][col])
if cur_d % 2 == 0:
cur_m += 1
if cur_m == m:
m -= 1
cur_d += 1
cur_d %= 4
cur_m = 0
else:
cur_n += 1
if cur_n == n:
n -= 1
cur_d += 1
cur_d %= 4
cur_n = 0
cur_p = (row + d[cur_d][0], col+d[cur_d][1])
return rlt

81
57-240605-pass/main.py Normal file
View File

@@ -0,0 +1,81 @@
class Solution:
def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:
l = newInterval[0]
r = newInterval[1]
if r < intervals[0][0]:
intervals.insert(0, newInterval)
return intervals
if l > intervals[-1][1]:
intervals.append(newInterval)
return intervals
nl = 0
nl_f = False
nl_ff = False
nr = len(intervals)
nr_f = False
nr_ff = False
for ind, interval in enumerate(intervals):
left = interval[0]
right = interval[1]
if l >= left and l <= right:
nl_f = True
nl = ind
if r >= left and r <= right:
nr_f = True
nr = ind + 1
if nl_f == False:
for i in range(1, len(intervals)):
if l > intervals[i - 1][1] and l < intervals[i][0]:
nl = i
nl_ff = True
break
if nr_f == False:
for i in range(1, len(intervals)):
if r > intervals[i - 1][1] and r < intervals[i][0]:
nr = i
nr_ff = True
break
print(nl, nr, nl_f, nr_f)
rlt = []
for i in range(nl):
rlt.append(intervals[i])
nl_l = intervals[nl][0]
if nl_f == False:
nl_l = l
if nr_ff == True or nr_f == True:
nr = nr - 1
nr_r = intervals[nr][1]
nr = nr + 1
if nr_f == False:
nr_r = r
rlt.append([nl_l, nr_r])
print(rlt)
for i in range(nr, len(intervals)):
rlt.append(intervals[i])
return rlt
intervals = [[1,3], [6,9]]
newInterval = [2,5]
sol = Solution()
print(sol.insert(intervals=intervals, newInterval=newInterval))
intervals = [[1,2], [3,5], [6,7], [8,10],[12, 16]]
newInterval = [4, 8]
print(sol.insert(intervals=intervals, newInterval=newInterval))
intervals = [[1,2], [3,5], [6,7], [8,10],[12, 16]]
newInterval = [0, 16]
print(sol.insert(intervals=intervals, newInterval=newInterval))
print()
intervals = [[1,5]]
newInterval = [6, 18]
print(sol.insert(intervals=intervals, newInterval=newInterval))

21
64-240603-pass/main.py Normal file
View File

@@ -0,0 +1,21 @@
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
r = []
for i in range(len(grid)):
r.append([])
for i , l in enumerate(grid):
for j, num in enumerate(l):
if i == 0 and j == 0:
r[i].append(num)
continue
if i == 0:
r[i].append(num + r[i][j - 1])
continue
if j == 0:
r[i].append(num + r[i - 1][0])
continue
r[i].append(min(r[i - 1][j], r[i][j - 1]) + num)
width = len(grid[0])
height = len(grid)
return r[height - 1][width - 1]

25
66-240603-pass/main.py Normal file
View File

@@ -0,0 +1,25 @@
class Solution:
def plusOne(self, digits: list[int]) -> list[int]:
flag = 1
# x = digits[-1] + 1
# if x == 10:
# flag = 1
# digits[-1] = 0
# else:
# digits[-1] = x
for i in range(len(digits) - 1, -1, -1):
x = digits[i] + flag
digits[i] = x
if x == 10:
flag = 1
digits[i] = 0
else:
flag = 0
if digits[0] == 0:
digits.insert(0, 1)
return digits
sol = Solution()
print(sol.plusOne([1, 2, 3]))
print(sol.plusOne([1, 2, 3, 4]))
print(sol.plusOne([9]))

13
74-240602-pass/main.py Normal file
View File

@@ -0,0 +1,13 @@
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
ind = len(matrix) - 1
for x, l in enumerate(matrix):
if l[0] < target: continue
if l[0] == target: return True
if x != 0: ind = x - 1
break
l = matrix[ind]
print(l)
if target in l:
return True
return False

13
77-240602-pass/main.py Normal file
View File

@@ -0,0 +1,13 @@
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
rlt = []
def comb(l, cur, k):
if k == 0:
rlt.append(l)
return
for i in range(cur, n + 1):
tmp_l = l.copy()
tmp_l.append(i)
comb(tmp_l, i + 1, k - 1)
comb([], 1, k)
return rlt

14
918-240623/main.cpp Normal file
View File

@@ -0,0 +1,14 @@
class Solution {
public:
int maxSubarraySumCircular(vector<int>& A) {
int sum = 0, mn = INT_MAX, mx = INT_MIN, curMax = 0, curMin = 0;
for (int num : A) {
curMin = min(curMin + num, num);
mn = min(mn, curMin);
curMax = max(curMax + num, num);
mx = max(mx, curMax);
sum += num;
}
return (sum - mn == 0) ? mx : max(mx, sum - mn);
}
};

25
92-240616-pass/main.py Normal file
View File

@@ -0,0 +1,25 @@
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
cnt = 0
l = []
true_head = ListNode()
true_head.next = head
true_end = ListNode()
cur = head
while cur.next != None:
cur = cur.next
cur.next = true_end
cur = true_head
while cur != None:
if cnt >= left - 1 and cnt <= right + 1:
l.append(cur)
cur = cur.next
cnt += 1
for ind in range(len(l), 0, -1):
l[ind].next = l[ind-1]