Compare commits
43 Commits
3630da98a0
...
master
Author | SHA1 | Date | |
---|---|---|---|
e95027872a | |||
045676e191 | |||
c944caec2e | |||
ed633c85b7 | |||
70b05fe146 | |||
321b2a8668 | |||
3a982c9b0c | |||
130ac22f05 | |||
3a451165d6 | |||
0f2f3b67d2 | |||
9087e2a0fe | |||
3184bf511e | |||
331fc02f5f | |||
9ca72f3125 | |||
|
0e82709984 | ||
|
d819c04697 | ||
886879c4d7 | |||
bccc78b194 | |||
|
3006568678 | ||
cdb6cccb89 | |||
40a4785d66 | |||
641f712a20 | |||
75690d88f7 | |||
|
9a925bccbb | ||
cd42299e73 | |||
9104fd9842 | |||
a295356ced | |||
757193083b | |||
21e70697e0 | |||
3a449cdf2a | |||
cf972fd868 | |||
b63eb3ed4d | |||
c03306f6e0 | |||
8b067e91be | |||
364ad7a999 | |||
98bf27748a | |||
7a8c262cb1 | |||
cb730dd7c7 | |||
0e9fec8a06 | |||
301d70cf8c | |||
9e8f43d107 | |||
8d5f40d02b | |||
713e1c9cea |
10
104-240525-pass/main.py
Normal file
10
104-240525-pass/main.py
Normal file
@@ -0,0 +1,10 @@
|
||||
class Solution:
|
||||
def hasCycle(self, head: Optional[ListNode]) -> bool:
|
||||
cnt = 0
|
||||
if head == None: return False
|
||||
while cnt < 1e4+10:
|
||||
if head.next == None:
|
||||
return False
|
||||
head = head.next
|
||||
cnt += 1
|
||||
return True
|
20
108-240525-pass/main.py
Normal file
20
108-240525-pass/main.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# Definition for a binary tree node.
|
||||
# class TreeNode:
|
||||
# def __init__(self, val=0, left=None, right=None):
|
||||
# self.val = val
|
||||
# self.left = left
|
||||
# self.right = right
|
||||
class Solution:
|
||||
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
|
||||
print(nums)
|
||||
if len(nums) == 0: return None
|
||||
mid = len(nums) // 2
|
||||
# if mid == 0 : return TreeNode(nums[mid], None, None)
|
||||
node = TreeNode(nums[mid], None, None)
|
||||
if mid != 0:
|
||||
left_nums = nums[:mid]
|
||||
node.left = self.sortedArrayToBST(left_nums)
|
||||
if mid + 1 < len(nums):
|
||||
right_nums = nums[mid + 1: ]
|
||||
node.right = self.sortedArrayToBST(right_nums)
|
||||
return node
|
63
130-240602-pass/main.py
Normal file
63
130-240602-pass/main.py
Normal 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
|
||||
|
BIN
138-240617-pass/.main.py.swp
Normal file
BIN
138-240617-pass/.main.py.swp
Normal file
Binary file not shown.
48
138-240617-pass/main.py
Normal file
48
138-240617-pass/main.py
Normal 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]
|
21
141-240525-pass/main.py
Normal file
21
141-240525-pass/main.py
Normal file
@@ -0,0 +1,21 @@
|
||||
# Definition for singly-linked list.
|
||||
class ListNode:
|
||||
def __init__(self, x):
|
||||
self.val = x
|
||||
self.next = None
|
||||
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, x):
|
||||
# self.val = x
|
||||
# self.next = None
|
||||
class Solution:
|
||||
def hasCycle(self, head: Optional[ListNode]) -> bool:
|
||||
cnt = 0
|
||||
if head == None: return False
|
||||
while cnt < 1e4+10:
|
||||
if head.next == None:
|
||||
return False
|
||||
head = head.next
|
||||
cnt += 1
|
||||
return True
|
0
150-240616-pass/main.py
Normal file
0
150-240616-pass/main.py
Normal file
43
155-240605-pass/main.py
Normal file
43
155-240605-pass/main.py
Normal 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
43
155-240605/main.py
Normal 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
19
167-240604-pass/main.py
Normal 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))
|
30
17-240525-pass/main.py
Normal file
30
17-240525-pass/main.py
Normal file
@@ -0,0 +1,30 @@
|
||||
class Solution:
|
||||
def letterCombinations(self, digits: str) -> List[str]:
|
||||
m = {
|
||||
1: '',
|
||||
2: 'abc',
|
||||
3: 'def',
|
||||
4: 'ghi',
|
||||
5: 'jkl',
|
||||
6: 'mno',
|
||||
7: 'pqrs',
|
||||
8: 'tuv',
|
||||
9: 'wxyz',
|
||||
}
|
||||
rlt = []
|
||||
for ch in digits:
|
||||
num = int(ch)
|
||||
if len(rlt) == 0:
|
||||
for l in m[num]:
|
||||
rlt.append(l)
|
||||
else:
|
||||
tmp_rlt = rlt.copy()
|
||||
for length in range(len(m[num])):
|
||||
ch = m[num][length]
|
||||
if length == 0:
|
||||
for index, s in enumerate(rlt):
|
||||
rlt[index] = tmp_rlt[index] + ch
|
||||
else:
|
||||
for index, s in enumerate(tmp_rlt):
|
||||
rlt.append(tmp_rlt[index] + ch)
|
||||
return rlt
|
20
190-240603-pass/main.py
Normal file
20
190-240603-pass/main.py
Normal 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
16
198-240603-pass/main.py
Normal 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]))
|
45
199-240525-pass/main.cpp
Normal file
45
199-240525-pass/main.cpp
Normal file
@@ -0,0 +1,45 @@
|
||||
#include<iostream>
|
||||
#include<vector>
|
||||
#include<queue>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct TreeNode {
|
||||
int val;
|
||||
TreeNode *left;
|
||||
TreeNode *right;
|
||||
TreeNode() : val(0), left(nullptr), right(nullptr) {}
|
||||
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
||||
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
|
||||
};
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> rightSideView(TreeNode* root) {
|
||||
queue<TreeNode *> que;
|
||||
vector<int> rlt;
|
||||
if(root == nullptr) return rlt;
|
||||
que.push(root);
|
||||
while(!que.empty()){
|
||||
queue< TreeNode *> tmp_que;
|
||||
TreeNode * node;
|
||||
while(!que.empty()){
|
||||
node = que.front();
|
||||
tmp_que.push(node);
|
||||
que.pop();
|
||||
}
|
||||
rlt.push_back(node->val);
|
||||
while(!tmp_que.empty()){
|
||||
node = tmp_que.front();
|
||||
if(node->left != nullptr){
|
||||
que.push(node->left);
|
||||
}
|
||||
if(node->right != nullptr){
|
||||
que.push(node->right);
|
||||
}
|
||||
tmp_que.pop();
|
||||
}
|
||||
}
|
||||
return rlt;
|
||||
}
|
||||
};
|
0
199-240525-pass/main.py
Normal file
0
199-240525-pass/main.py
Normal file
42
20-240526-pass/main.py
Normal file
42
20-240526-pass/main.py
Normal file
@@ -0,0 +1,42 @@
|
||||
class Solution:
|
||||
def isValid(self, s: str) -> bool:
|
||||
def rcg_type(ch) -> int:
|
||||
if ch[0] =='(':
|
||||
return 1
|
||||
if ch[0] ==')':
|
||||
return 2
|
||||
if ch[0] =='{':
|
||||
return 3
|
||||
if ch[0] =='}':
|
||||
return 4
|
||||
if ch[0] =='[':
|
||||
return 5
|
||||
if ch[0] ==']':
|
||||
return 6
|
||||
stack = []
|
||||
top_idx = -1
|
||||
def is_empty():
|
||||
return top_idx == -1
|
||||
def set_ele(stack: list, idx: int, ele: int):
|
||||
if len(stack) <= idx:
|
||||
stack.append(ele)
|
||||
else:
|
||||
stack[idx] = ele
|
||||
for ch in s:
|
||||
tp = rcg_type(ch)
|
||||
if tp % 2 == 1:
|
||||
top_idx += 1
|
||||
set_ele(stack, top_idx, tp)
|
||||
else:
|
||||
if is_empty(): return False
|
||||
top_ele = stack[top_idx]
|
||||
if tp - top_ele != 1: return False
|
||||
top_idx -= 1
|
||||
if not is_empty(): return False
|
||||
return True
|
||||
|
||||
sol = Solution()
|
||||
print(sol.isValid("()"))
|
||||
print(sol.isValid("(){}[]"))
|
||||
print(sol.isValid("(]"))
|
||||
print(sol.isValid("[(])"))
|
58
200-240525-pass/main.py
Normal file
58
200-240525-pass/main.py
Normal file
@@ -0,0 +1,58 @@
|
||||
class Solution:
|
||||
def numIslands(self, grid: List[List[str]]) -> int:
|
||||
searched_cell = set()
|
||||
def va(s):
|
||||
return int(s)
|
||||
# bfs
|
||||
ans = 0
|
||||
row = len(grid)
|
||||
column = len(grid[0])
|
||||
def add_node(que, idx, node):
|
||||
if len(que) <= idx:
|
||||
que.append(node)
|
||||
else:
|
||||
que[idx] = node
|
||||
def is_valid_node(node):
|
||||
i = node[0]
|
||||
j = node[1]
|
||||
return i >= 0 and j >= 0 and i < row and j <column
|
||||
flag = []
|
||||
for i, l in enumerate(grid):
|
||||
flag.append([])
|
||||
for j, lee in enumerate(l):
|
||||
flag[i].append(0)
|
||||
for i, l in enumerate(grid):
|
||||
for j, ele in enumerate(l):
|
||||
val = va(grid[i][j])
|
||||
if val == 0 : continue
|
||||
# if (i,j) in searched_cell: continue
|
||||
if flag[i][j] == 1: continue
|
||||
que = [(i, j)]
|
||||
idx = 0
|
||||
while idx >= 0:
|
||||
node = que[idx]
|
||||
# if node in searched_cell: continue
|
||||
idx -= 1
|
||||
if flag[node[0]][node[1]] == 1: continue
|
||||
flag[node[0]][node[1]] = 1
|
||||
if va(grid[node[0]][node[1]]) == 0: continue
|
||||
up = (node[0] - 1, node[1])
|
||||
down = (node[0] + 1, node[1])
|
||||
left = (node[0], node[1] - 1)
|
||||
right = (node[0], node[1] + 1)
|
||||
if is_valid_node(up):
|
||||
idx += 1
|
||||
add_node(que, idx, up)
|
||||
if is_valid_node(down):
|
||||
idx += 1
|
||||
add_node(que,idx, down)
|
||||
if is_valid_node(left):
|
||||
idx += 1
|
||||
add_node(que, idx, left)
|
||||
if is_valid_node(right):
|
||||
idx += 1
|
||||
add_node(que,idx, right)
|
||||
ans += 1
|
||||
return ans
|
||||
|
||||
|
26
208-240525-pass/main.py
Normal file
26
208-240525-pass/main.py
Normal file
@@ -0,0 +1,26 @@
|
||||
class Trie:
|
||||
|
||||
def __init__(self):
|
||||
self.l = []
|
||||
|
||||
def insert(self, word: str) -> None:
|
||||
self.l.append(word)
|
||||
|
||||
def search(self, word: str) -> bool:
|
||||
for s in self.l:
|
||||
if s == word:
|
||||
return True
|
||||
return False
|
||||
|
||||
def startsWith(self, prefix: str) -> bool:
|
||||
for s in self.l:
|
||||
if s.startswith(prefix):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# Your Trie object will be instantiated and called as such:
|
||||
# obj = Trie()
|
||||
# obj.insert(word)
|
||||
# param_2 = obj.search(word)
|
||||
# param_3 = obj.startsWith(prefix)
|
42
208-240525-pass/main1.py
Normal file
42
208-240525-pass/main1.py
Normal file
@@ -0,0 +1,42 @@
|
||||
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:
|
||||
parent_node = self.root
|
||||
for idx, letter in enumerate(word):
|
||||
if letter not in parent_node.child_map:
|
||||
return False
|
||||
idx = parent_node.child_map[letter]
|
||||
parent_node = parent_node.child[idx]
|
||||
if parent_node.is_word == False:
|
||||
return False
|
||||
return True
|
||||
|
||||
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
|
71
211-240602-pass/main.py
Normal file
71
211-240602-pass/main.py
Normal 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)
|
29
228-240525-pass/main.py
Normal file
29
228-240525-pass/main.py
Normal file
@@ -0,0 +1,29 @@
|
||||
class Solution:
|
||||
def summaryRanges(self, nums: list[int]) -> list[str]:
|
||||
if len(nums) == 0:
|
||||
return []
|
||||
rlt = []
|
||||
start = nums[0]
|
||||
end = start
|
||||
last = start
|
||||
for idx, ele in enumerate(nums[1:]):
|
||||
if ele == last + 1:
|
||||
end = ele
|
||||
else:
|
||||
rlt.append((start, end))
|
||||
start = ele
|
||||
end = ele
|
||||
last = ele
|
||||
rlt.append((start,end))
|
||||
str_rlt = []
|
||||
for ele in rlt:
|
||||
if ele[0] == ele[1]:
|
||||
str_rlt.append(f"{ele[0]}")
|
||||
else:
|
||||
str_rlt.append(f"{ele[0]}->{ele[1]}")
|
||||
return str_rlt
|
||||
|
||||
sol = Solution()
|
||||
print(sol.summaryRanges([0,1,2,4,5,7]))
|
||||
print(sol.summaryRanges([0,2,3,4,6,8,9]))
|
||||
|
10
26-240604-pass/main.py
Normal file
10
26-240604-pass/main.py
Normal 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
|
18
27-240525-pass/main.py
Normal file
18
27-240525-pass/main.py
Normal file
@@ -0,0 +1,18 @@
|
||||
class Solution:
|
||||
def removeElement(self, nums: list[int], val: int) -> int:
|
||||
cnt = 0
|
||||
for num in nums:
|
||||
if num == val: cnt+=1
|
||||
for i in range(len(nums) - cnt):
|
||||
if nums[i] == val:
|
||||
for j in range(len(nums) - 1, 0, -1):
|
||||
if nums[j] != val:
|
||||
nums[i], nums[j] = (nums[j], nums[i])
|
||||
print(nums)
|
||||
return len(nums) - cnt
|
||||
|
||||
nums = [3, 2, 2, 3]
|
||||
val = 3
|
||||
sol = Solution()
|
||||
print(sol.removeElement(nums, val))
|
||||
|
36
3-240603-pass/main.py
Normal file
36
3-240603-pass/main.py
Normal 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
146
30-240604/main.py
Normal 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"]))
|
||||
|
17
35-240525-pass/main.py
Normal file
17
35-240525-pass/main.py
Normal file
@@ -0,0 +1,17 @@
|
||||
class Solution:
|
||||
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||
left = 0
|
||||
right = len(nums)
|
||||
while left < right:
|
||||
mid = (left + right) // 2
|
||||
print(mid, nums[mid])
|
||||
if nums[mid] == target: return mid
|
||||
elif nums[mid] < target:
|
||||
left = mid
|
||||
elif nums[mid] > target:
|
||||
right = mid
|
||||
if right - left == 1:
|
||||
if target > nums[left]: return right
|
||||
else: return left
|
||||
print(left, right, mid)
|
||||
return 0
|
74
36-240525-pass/main.py
Normal file
74
36-240525-pass/main.py
Normal file
@@ -0,0 +1,74 @@
|
||||
class Solution:
|
||||
def isValidSudoku(self, board: list[list[str]]) -> bool:
|
||||
plates = []
|
||||
for l in board:
|
||||
plates.append([])
|
||||
for ch_num in l:
|
||||
if ch_num.isalnum():
|
||||
num = int(ch_num[0])
|
||||
else:
|
||||
num = -1
|
||||
plates[-1].append(num)
|
||||
def judge_1(plates, i, j):
|
||||
t = plates[i][j]
|
||||
for idx, num in enumerate(plates[i]):
|
||||
if idx == j: continue
|
||||
if num == t: return False
|
||||
return True
|
||||
|
||||
def judge_2(plates, i, j):
|
||||
t = plates[i][j]
|
||||
l = []
|
||||
for idx in range(0, 9):
|
||||
l.append(plates[idx][j])
|
||||
for idx, num in enumerate(l):
|
||||
if idx == i: continue
|
||||
if num == t: return False
|
||||
return True
|
||||
|
||||
def judge_3(plates, i, j):
|
||||
row = i // 3 * 3
|
||||
col = j // 3 * 3
|
||||
l = []
|
||||
for idx1 in range(row, row + 3):
|
||||
for idx2 in range(col, col + 3):
|
||||
if idx1 == i and idx2 ==j: continue
|
||||
l.append(plates[idx1][idx2])
|
||||
for idx,num in enumerate(l):
|
||||
if num == plates[i][j]:
|
||||
return False
|
||||
return True
|
||||
|
||||
for i in range(0, 9):
|
||||
for j in range(0, 9):
|
||||
if plates[i][j] == -1: continue
|
||||
if not judge_1(plates, i, j):
|
||||
return False
|
||||
if not judge_2(plates, i, j):
|
||||
return False
|
||||
if not judge_3(plates, i, j):
|
||||
return False
|
||||
return True
|
||||
|
||||
board = [["5","3",".",".","7",".",".",".","."]
|
||||
,["6",".",".","1","9","5",".",".","."]
|
||||
,[".","9","8",".",".",".",".","6","."]
|
||||
,["8",".",".",".","6",".",".",".","3"]
|
||||
,["4",".",".","8",".","3",".",".","1"]
|
||||
,["7",".",".",".","2",".",".",".","6"]
|
||||
,[".","6",".",".",".",".","2","8","."]
|
||||
,[".",".",".","4","1","9",".",".","5"]
|
||||
,[".",".",".",".","8",".",".","7","9"]]
|
||||
|
||||
sol = Solution()
|
||||
print(sol.isValidSudoku(board=board))
|
||||
board = [["8","3",".",".","7",".",".",".","."]
|
||||
,["6",".",".","1","9","5",".",".","."]
|
||||
,[".","9","8",".",".",".",".","6","."]
|
||||
,["8",".",".",".","6",".",".",".","3"]
|
||||
,["4",".",".","8",".","3",".",".","1"]
|
||||
,["7",".",".",".","2",".",".",".","6"]
|
||||
,[".","6",".",".",".",".","2","8","."]
|
||||
,[".",".",".","4","1","9",".",".","5"]
|
||||
,[".",".",".",".","8",".",".","7","9"]]
|
||||
print(sol.isValidSudoku(board=board))
|
27
383-240524-pass/main.py
Normal file
27
383-240524-pass/main.py
Normal file
@@ -0,0 +1,27 @@
|
||||
class Solution:
|
||||
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
|
||||
ran_dic = {}
|
||||
mag_dic = {}
|
||||
for l in ransomNote:
|
||||
if l not in ran_dic:
|
||||
ran_dic[l] = 1
|
||||
else:
|
||||
ran_dic[l] += 1
|
||||
for l in magazine:
|
||||
if l not in mag_dic:
|
||||
mag_dic[l] = 1
|
||||
else:
|
||||
mag_dic[l] += 1
|
||||
print(ran_dic)
|
||||
print(mag_dic)
|
||||
for key in ran_dic:
|
||||
if key not in mag_dic:
|
||||
return False
|
||||
if ran_dic[key] > mag_dic[key]:
|
||||
return False
|
||||
return True
|
||||
|
||||
sol = Solution()
|
||||
print(sol.canConstruct("a", "b"))
|
||||
print(sol.canConstruct("aa", "ab"))
|
||||
print(sol.canConstruct("aa", "aab"))
|
16
39-240619-pass/main.py
Normal file
16
39-240619-pass/main.py
Normal 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))
|
17
392-240527-pass/main.py
Normal file
17
392-240527-pass/main.py
Normal file
@@ -0,0 +1,17 @@
|
||||
class Solution:
|
||||
def isSubsequence(self, s: str, t: str) -> bool:
|
||||
cnt = 0
|
||||
idt_m = 0
|
||||
for idx, chs in enumerate(s):
|
||||
for idt, cht in enumerate(t[idt_m:]):
|
||||
if cht == chs:
|
||||
idt_m = idt + idt_m + 1
|
||||
cnt += 1
|
||||
break
|
||||
if cnt == len(s): return True
|
||||
return False
|
||||
|
||||
sol = Solution()
|
||||
s = "axc"
|
||||
t = "ahbgdc"
|
||||
print(sol.isSubsequence(s,t))
|
55
399-240619-pass/main.py
Normal file
55
399-240619-pass/main.py
Normal 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
41
427-240611-pass/main.py
Normal 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
38
433-240602-pass/main.py
Normal 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
18
452-240616-pass/main.py
Normal 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
26
46-240610-pass/main.py
Normal 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]))
|
||||
|
10
53-240525-pass/main.py
Normal file
10
53-240525-pass/main.py
Normal file
@@ -0,0 +1,10 @@
|
||||
class Solution:
|
||||
def maxSubArray(self, nums: List[int]) -> int:
|
||||
s = [-1e5]
|
||||
for index, num in enumerate(nums):
|
||||
val = max(s[index] + num, num)
|
||||
s.append(val)
|
||||
ans = -1e5
|
||||
for num in s:
|
||||
ans = max(num,ans)
|
||||
return ans
|
32
530-240525-pass/main.py
Normal file
32
530-240525-pass/main.py
Normal file
@@ -0,0 +1,32 @@
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> rightSideView(TreeNode* root) {
|
||||
queue<TreeNode *> que;
|
||||
vector<int> rlt;
|
||||
if(root->left == nullptr && root->right == nullptr){
|
||||
return rlt;
|
||||
}
|
||||
que.push(root);
|
||||
while(!que.empty()){
|
||||
queue< TreeNode *> tmp_que;
|
||||
TreeNode * node;
|
||||
while(!que.empty()){
|
||||
node = que.front();
|
||||
tmp_que.push(node);
|
||||
que.pop();
|
||||
}
|
||||
rlt.push_back(node->val);
|
||||
while(!tmp_que.empty()){
|
||||
node = tmp_que.front();
|
||||
if(node->left != nullptr){
|
||||
que.push(node->left);
|
||||
}
|
||||
if(node->right != nullptr){
|
||||
que.push(node->right);
|
||||
}
|
||||
tmp_que.pop();
|
||||
}
|
||||
}
|
||||
return rlt;
|
||||
}
|
||||
};
|
32
54-240608-pass/main.py
Normal file
32
54-240608-pass/main.py
Normal 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
|
18
56-240602-pass/main.py
Normal file
18
56-240602-pass/main.py
Normal file
@@ -0,0 +1,18 @@
|
||||
class Solution:
|
||||
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
|
||||
sorted_intervals = sorted(intervals, key=lambda x:x[0])
|
||||
cur_l = [sorted_intervals[0][0], sorted_intervals[0][1]]
|
||||
rlt = []
|
||||
for ind, l in enumerate(sorted_intervals[1:]):
|
||||
|
||||
if cur_l[1] >= l[1] and cur_l[0]<=l[0]:pass
|
||||
elif cur_l[1] >= l[0]:
|
||||
cur_l[1] = l[1]
|
||||
else:
|
||||
r = cur_l.copy()
|
||||
rlt.append(r)
|
||||
cur_l[0]=l[0]
|
||||
cur_l[1]=l[1]
|
||||
# print(cur_l,rlt)
|
||||
rlt.append(cur_l)
|
||||
return rlt
|
81
57-240605-pass/main.py
Normal file
81
57-240605-pass/main.py
Normal 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
21
64-240603-pass/main.py
Normal 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
25
66-240603-pass/main.py
Normal 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]))
|
33
67-240525-pass/main.py
Normal file
33
67-240525-pass/main.py
Normal file
@@ -0,0 +1,33 @@
|
||||
class Solution:
|
||||
def addBinary(self, a: str, b: str) -> str:
|
||||
tmpa = a
|
||||
tmpb = b
|
||||
if len(a)>len(b):
|
||||
a = tmpb
|
||||
b = tmpa
|
||||
while len(a) < len(b): a = '0' + a
|
||||
print(a, b)
|
||||
flag = 0
|
||||
indb = len(b) - 1
|
||||
rlt = ""
|
||||
for inda in range(len(a)-1, -1, -1):
|
||||
numa = int(a[inda])
|
||||
numb = int(b[indb])
|
||||
s = numa + numb + flag
|
||||
print(s)
|
||||
if s == 3:
|
||||
rlt = '1' + rlt
|
||||
flag = 1
|
||||
if s == 2:
|
||||
flag = 1
|
||||
rlt = '0' + rlt
|
||||
if s == 1:
|
||||
flag = 0
|
||||
rlt = '1' + rlt
|
||||
if s == 0:
|
||||
flag = 0
|
||||
rlt = '0' + rlt
|
||||
indb -= 1
|
||||
print(f'rlt: {rlt}')
|
||||
if flag == 1: rlt = '1' + rlt
|
||||
return rlt
|
13
74-240602-pass/main.py
Normal file
13
74-240602-pass/main.py
Normal 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
13
77-240602-pass/main.py
Normal 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
|
15
9-240525-pass/main.py
Normal file
15
9-240525-pass/main.py
Normal file
@@ -0,0 +1,15 @@
|
||||
class Solution:
|
||||
def isPalindrome(self, x: int) -> bool:
|
||||
s = str(x)
|
||||
if len(s) % 2 == 0:
|
||||
mid = len(s) // 2 - 1
|
||||
for i in range(mid):
|
||||
if s[i] != s[len(s) - i - 1]:
|
||||
return False
|
||||
return True
|
||||
else:
|
||||
mid = len(s) // 2
|
||||
for i in range(mid):
|
||||
if s[i] != s[len(s) - i - 1]:
|
||||
return False
|
||||
return True
|
46
909-240525-pass/main.py
Normal file
46
909-240525-pass/main.py
Normal file
@@ -0,0 +1,46 @@
|
||||
class Solution:
|
||||
def snakesAndLadders(self, board: List[List[int]]) -> int:
|
||||
ans = 0
|
||||
n = len(board)
|
||||
n = n - 1
|
||||
length = n + 1
|
||||
que = [(1,0)]
|
||||
idx = 0
|
||||
flag = [0 for i in range((n+1)*(n+1))]
|
||||
def add_node(que, idx, node):
|
||||
if len(que) <= idx:
|
||||
que.append(node)
|
||||
else:
|
||||
que[idx] = node
|
||||
def move(idx):
|
||||
row = 0
|
||||
column = idx % (n + 1)
|
||||
if idx % (n + 1) == 0: row -= 1
|
||||
row += idx // (n + 1)
|
||||
row = n - row
|
||||
oe = idx // (n + 1) % 2
|
||||
if idx % (n + 1) == 0: oe = 1 - oe
|
||||
if column == 0: column = n + 1
|
||||
column -= 1
|
||||
if oe == 1: column = n - column
|
||||
return (row, column)
|
||||
front = 0
|
||||
while idx - front >= 0:
|
||||
node = que[front]
|
||||
front += 1
|
||||
step = node[1]
|
||||
cur_loc = node[0]
|
||||
if flag[cur_loc] == 1: continue
|
||||
flag[cur_loc] = 1
|
||||
if cur_loc + 6 >= length * length:
|
||||
return step + 1
|
||||
for i in range(1, 7):
|
||||
(row, column) = move(i + cur_loc)
|
||||
if board[row][column]!= -1:
|
||||
if board[row][column] == length * length: return step + 1
|
||||
idx += 1
|
||||
add_node(que, idx, (board[row][column], step + 1))
|
||||
else:
|
||||
idx += 1
|
||||
add_node(que, idx, (i + cur_loc, step + 1))
|
||||
return -1
|
14
918-240623/main.cpp
Normal file
14
918-240623/main.cpp
Normal 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
25
92-240616-pass/main.py
Normal 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]
|
||||
|
103
sample.cpp
Normal file
103
sample.cpp
Normal file
@@ -0,0 +1,103 @@
|
||||
#include<iostream>
|
||||
#include<vector>
|
||||
#include<set>
|
||||
#include<algorithm>
|
||||
using namespace std;
|
||||
|
||||
class Solution{
|
||||
public:
|
||||
struct Point{
|
||||
int x;
|
||||
int y;
|
||||
bool operator<(const Point& other) const{
|
||||
if (x!=other.x)return x<other.x;
|
||||
return y < other.y;
|
||||
}
|
||||
};
|
||||
|
||||
static bool cmp(const Point &a, const Point &b){
|
||||
return a.x < b.x ||(a.x == b.x && a.y < b.y);
|
||||
}
|
||||
static bool cmp1(const Point &a, const Point &b){
|
||||
return a.y < b.y ||(a.y == b.y && a.x < b.x);
|
||||
}
|
||||
void print_vec(set<Point> x){
|
||||
for(auto e: x){
|
||||
cout<<'('<<e.x<<','<<e.y<<"), ";
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
int numIdleDrives(vector<int> x, vector<int> y){
|
||||
|
||||
vector<Point> poi;
|
||||
set<Point> hor;
|
||||
set<Point> ver;
|
||||
|
||||
int n = x.size();
|
||||
for(int i = 0 ; i < n ; i++){
|
||||
poi.push_back({x[i], y[i]});
|
||||
}
|
||||
sort(poi.begin(), poi.end(), cmp);
|
||||
int cur_x = poi[0].x;
|
||||
int sum_x = 0;
|
||||
Point last_point = poi[0];
|
||||
hor.insert(last_point);
|
||||
// horizontal
|
||||
for(int i = 1 ; i < n ; i++){
|
||||
Point cur_p = poi[i];
|
||||
if(cur_p.x == cur_x){
|
||||
sum_x += 1;
|
||||
}
|
||||
else{
|
||||
if(sum_x >= 2)
|
||||
hor.insert(last_point);
|
||||
hor.insert(cur_p);
|
||||
sum_x = 1;
|
||||
cur_x = cur_p.x;
|
||||
}
|
||||
last_point = cur_p;
|
||||
}
|
||||
//vertical
|
||||
sort(poi.begin(), poi.end(), cmp1);
|
||||
int cur_y = poi[0].y;
|
||||
int sum_y = 1;
|
||||
last_point = poi[0];
|
||||
ver.insert(last_point);
|
||||
for(int i = 1 ; i < n ; i++){
|
||||
Point cur_p = poi[i];
|
||||
if(cur_p.y == cur_y){
|
||||
sum_y += 1;
|
||||
}
|
||||
else{
|
||||
if(sum_y >= 2)
|
||||
ver.insert(last_point);
|
||||
ver.insert(cur_p);
|
||||
sum_y = 1;
|
||||
cur_y = cur_p.y;
|
||||
}
|
||||
last_point = cur_p;
|
||||
}
|
||||
set<Point> rlt;
|
||||
for(const auto& point : ver){
|
||||
rlt.insert(point);
|
||||
}
|
||||
for(const auto& point : hor){
|
||||
rlt.insert(point);
|
||||
}
|
||||
|
||||
return n - rlt.size();
|
||||
}
|
||||
};
|
||||
int main(){
|
||||
Solution *sol = new Solution();
|
||||
vector<int>x = {0, 0, 0, 0, 0, 1, 1, 1, 2, -1, -1, -2, -1};
|
||||
vector<int>y = {-1, 0, 1, 2, -2, 0, 1, -1, 0, 1, -1, 0, 0};
|
||||
cout<<sol->numIdleDrives(x,y)<<endl;
|
||||
vector<int>x1 = {1, 1, 1, 2, 2, 2, 2, 3, 3, 3};
|
||||
vector<int>y1 = {1, 2, 3, 1, 2, 3, 5, 1, 2, 3};
|
||||
cout<<sol->numIdleDrives(x1,y1)<<endl;
|
||||
vector<int>x2 = {0, -1,0,0,3,5,4,4,4};
|
||||
vector<int>y2 = {0,0,1,-1,0,0,1,-1,0};
|
||||
cout<<sol->numIdleDrives(x2,y2)<<endl;
|
||||
}
|
||||
// {0,1},{0,4},{1,0},{2,2},{1,3},{0,4},{2,5},{3,4}
|
19
sample.py
Normal file
19
sample.py
Normal file
@@ -0,0 +1,19 @@
|
||||
def makePowerNonDecreasing(power):
|
||||
# Write your code here
|
||||
res=0
|
||||
gap=0
|
||||
while len(power)>1:
|
||||
power[1]+=res
|
||||
print(power, res)
|
||||
if power[1]>=power[0]:
|
||||
power.pop(0)
|
||||
else:
|
||||
gap=power[0]-power[1]
|
||||
res+=gap
|
||||
power.pop(0)
|
||||
power[0]+=gap
|
||||
print(power, res)
|
||||
return res
|
||||
|
||||
res = makePowerNonDecreasing([3,5,2,6,3])
|
||||
print(res)
|
Reference in New Issue
Block a user