classSolution:
defReverseList(self, head: ListNode) -> ListNode:
# write code here
pre = Nonewhile head:
tmp = head.next
head.next = pre
pre = head
head = tmp
return pre
BM2 链表内指定区间反转
classSolution:
defreverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# write code here
dummy = ListNode(-1)
dummy.next = head
pre = dummy
for i inrange(m - 1):
pre = pre.next
cur = pre.nextfor i inrange(n - m):
tmp = cur.next
cur.next = tmp.next
tmp.next = pre.next
pre.next = tmp
return dummy.next
BM3 链表中的节点每 k 个一组翻转
classSolution:
def () -> ListNode:
a = []
s = []
head:
a.append(head.val)
head = head.
(a) == k:
s.extend(a[::-])
a = []
(a) < k:
s.extend(a)
dummy = ListNode(-)
pre = dummy
num s:
node = ListNode(num)
pre. = node
pre = node
dummy.
reverseKGroup
self, head: ListNode, k: int
# write code here
while
next
if
len
1
if
len
1
for
in
next
return
next
BM4 合并两个排序的链表
classSolution:
defMerge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
# write code here
dummy = ListNode(0)
cur = dummy
p1, p2 = pHead1, pHead2
while p1 and p2:
if p1.val <= p2.val:
cur.next = p1
p1 = p1.nextelse:
cur.next = p2
p2 = p2.next
cur = cur.next
cur.next = p1 if p1 else p2
return dummy.next
BM5 合并 k 个已排序的链表
classSolution:
defmerge(self, p1, p2):
dummy = ListNode(-1)
pre = dummy
while p1 and p2:
if p1.val <= p2.val:
pre.next = p1
p1 = p1.nextelse:
pre.next = p2
p2 = p2.next
pre = pre.next
pre.next = p1 if p1 else p2
return dummy.nextdefmergeKLists(self, lists: List[ListNode]) -> ListNode:
# write code hereifnot lists:
returnNone
res = lists[0]
for i inrange(1, len(lists)):
res = self.merge(res, lists[i])
return res
BM6 判断链表中是否有环
classSolution:
defhasCycle(self, head: ListNode) -> bool:
s = set()
while head:
if head in s:
returnTrueelse:
s.add(head)
head = head.nextreturnFalse
BM7 链表中环的入口结点
classSolution:
defEntryNodeOfLoop(self, pHead):
# write code here
slow, fast = pHead, pHead
while fast and fast.next:
slow = slow.next
fast = fast.next.nextif slow == fast:
breakifnot fast ornot fast.next:
returnNone
slow = pHead
while slow != fast:
slow = slow.next
fast = fast.nextreturn slow
BM8 链表中倒数最后 k 个结点
classSolution:
defFindKthToTail(self, pHead: ListNode, k: int) -> ListNode:
# write code here
fast, slow = pHead, pHead
while k > 0and fast:
k -= 1
fast = fast.nextif k > 0:
returnNonewhile fast:
fast = fast.next
slow = slow.nextreturn slow
BM9 删除链表的倒数第 n 个节点
classSolution:
defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# write code here
dummy = ListNode(-1)
dummy.next = head
pre = dummy
cur = head
for i inrange(n):
cur = cur.nextwhile cur:
cur = cur.next
pre = pre.next
pre.next = pre.next.nextreturn dummy.next
classSolution:
defaddInList(self, head1: ListNode, head2: ListNode) -> ListNode:
# write code here
nums1, nums2 = [], []
while head1:
nums1.append(head1.val)
head1 = head1.nextwhile head2:
nums2.append(head2.val)
head2 = head2.next
s, c = 0, 0
tmp = Nonewhile nums1 or nums2:
if nums1 and nums2:
s = nums1.pop() + nums2.pop() + c
s1 = s % 10
c = s // 10
node = ListNode(s1)
node.next = tmp
tmp = node
elif nums1:
s = nums1.pop() + c
s1 = s % 10
c = s // 10
node = ListNode(s1)
node.next = tmp
tmp = node
else:
s = nums2.pop() + c
s1 = s % 10
c = s // 10
node = ListNode(s1)
node.next = tmp
tmp = node
if c:
node = ListNode(c)
node.next = tmp
tmp = node
return tmp
BM12 单链表的排序
classSolution:
defsortInList(self, head: ListNode) -> ListNode:
# write code hereifnot head ornot head.next:
return head
slow, fast = head, head.nextwhile fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
left = self.sortInList(head)
right = self.sortInList(mid)
dummy = cur = ListNode(-1)
while left and right:
if left.val <= right.val:
cur.next = left
left = left.nextelse:
cur.next = right
right = right.next
cur = cur.next
cur.next = left if left else right
return dummy.next
BM13 判断一个链表是否为回文结构
classSolution:
defisPail(self, head: ListNode) -> bool:
# write code here
s = []
while head:
s.append(head.val)
head = head.nextreturn s == s[::-1]
BM14 链表的奇偶重排
classSolution:
defoddEvenList(self, head: ListNode) -> ListNode:
# write code hereifnot head ornot head.next:
return head
evenhead = head.next
odd, even = head, evenhead
while even and even.next:
odd.next = even.next
odd = even.next
even.next = odd.next
even = odd.next
odd.next = evenhead
return head
BM15 删除有序链表中重复的元素-I
classSolution:
defdeleteDuplicates(self, head: ListNode) -> ListNode:
# write code here
cur = head
ifnot head ornot head.next:
return head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.nextelse:
cur = cur.nextreturn head
BM16 删除有序链表中重复的元素-II
classSolution:
defdeleteDuplicates(self, head: ListNode) -> ListNode:
# write code here
dummy = pre = ListNode(-1)
dummy.next = head
cur = head
while cur:
while cur.nextand cur.val == cur.next.val:
cur = cur.nextif pre.next == cur:
pre = cur
else:
pre.next = cur.next
cur = cur.nextreturn dummy.next
BM17 二分查找-I
classSolution:
defsearch(self, nums: List[int], target: int) -> int:
# write code hereifnot nums:
return -1
l, r = 0, len(nums)
while l <= r:
mid = l + (r - l) // 2if nums[mid] == target:
return mid
elif nums[mid] < target:
l = mid + 1else:
r = mid - 1return -1
BM18 二维数组中的查找
classSolution:
defFind(self, target: int, array: List[List[int]]) -> bool:
# write code heredefbinary(target, nums):
ifnot nums:
returnFalse
l, r = 0, len(nums) - 1while l <= r:
mid = l + (r - l) // 2if nums[mid] == target:
returnTrueelif nums[mid] < target:
l = mid + 1else:
r = mid - 1returnFalsefor nums in array:
result = binary(target, nums)
if result:
return result
returnFalse
BM19 寻找峰值
classSolution:
deffindPeakElement(self, nums: List[int]) -> int:
# write code here
l, r = 0, len(nums) - 1while l < r:
mid = (r + l) // 2if nums[mid] <= nums[mid + 1]:
l = mid + 1else:
r = mid
return l
BM20 数组中的逆序对
classSolution:
defrr(self, data):
iflen(data) < 2:
return0
big, small = [], []
ans = 0
pre = data[0]
for num in data[1:]:
if num > pre:
big.append(num)
else:
small.append(num)
ans += len(big) + 1return ans + self.rr(big) + self.rr(small)
defInversePairs(self, nums: List[int]) -> int:
# write code herereturnself.rr(nums) % 1000000007
BM21 旋转数组的最小数字
classSolution:
defminNumberInRotateArray(self, nums: List[int]) -> int:
# write code here
l, r = 0, len(nums) - 1while l < r:
mid = (l + r) // 2if nums[mid] > nums[r]:
l = mid + 1elif nums[mid] < nums[l]:
r = mid
else:
r -= 1return nums[l]
classSolution:
definorder(self, l, root):
ifnot root:
returnif root.left:
self.inorder(l, root.left)
l.append(root.val)
if root.right:
self.inorder(l, root.right)
definorderTraversal(self, root: TreeNode) -> List[int]:
# write code here
l = []
self.inorder(l, root)
return l
BM25 二叉树的后序遍历
classSolution:
defpostorder(self, l, root):
ifnot root:
returnself.postorder(l, root.left)
self.postorder(l, root.right)
l.append(root.val)
defpostorderTraversal(self, root: TreeNode) -> List[int]:
# write code here
l = []
self.postorder(l, root)
return l
BM26 二叉树的层序遍历
classSolution:
deflevelOrder(self, root: TreeNode) -> List[List[int]]:
# write code here
res = []
ifnot root:
return res
q = []
q.append(root)
while q:
path = []
for i inrange(len(q)):
root = q.pop(0)
path.append(root.val)
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
res.append(path)
return res
BM27 按之字形顺序打印二叉树
classSolution:
defPrint(self, pRoot: TreeNode) -> List[List[int]]:
# write code hereifnot pRoot:
return []
q = [pRoot]
res = []
flag = Truewhile q:
path = []
for i inrange(len(q)):
root = q.pop(0)
path.append(root.val)
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
if flag:
res.append(path)
else:
res.append(path[::-1])
flag = not flag
return res
classSolution:
A = []
B = []
defpush(self, node):
# write code hereself.A.append(node)
ifnotself.B or node <= self.B[-1]:
self.B.append(node)
defpop(self):
# write code here
val = self.A.pop()
ifself.B[-1] == val:
self.B.pop()
return val
deftop(self):
# write code herereturnself.A[-1]
defmin(self):
# write code herereturnself.B[-1]
BM44 有效括号序列
classSolution:
defisValid(self, s: str) -> bool:
# write code here
A = []
for c in s:
if c == '('or c == '{'or c == '[':
A.append(c)
elif c == ')':
ifnot A or A.pop() != '(':
returnFalseelif c == ']':
ifnot A or A.pop() != '[':
returnFalseelif c == '}':
ifnot A or A.pop() != '{':
returnFalseelse:
returnFalsereturnnot A
BM45 滑动窗口的最大值
classSolution:
defmaxInWindows(self, num: List[int], size: int) -> List[int]:
# 维持一个单调递减队列ifnot size:
return []
res = []
queue = []
for i inrange(len(num)):
if queue and i - queue[0] + 1 > size:
queue.pop(0)
while queue and num[queue[-1]] < num[i]:
queue.pop()
queue.append(i)
if i - size + 1 >= 0:
res.append(num[queue[0]])
return res
classSolution:
deffindKth(self, a: List[int], n: int, K: int) -> int:
# write code heredefquicksort(a, l, r):
if l > r:
return -1
pivot = a[l]
low, up = l, r
while l < r:
while l < r and a[r] <= pivot:
r -= 1while l < r and a[l] >= pivot:
l += 1
a[l], a[r] = a[r], a[l]
a[l], a[low] = a[low], a[l]
if l == K - 1:
return a[l]
elif l < K - 1:
return quicksort(a, l + 1, up)
else:
return quicksort(a, low, l - 1)
return quicksort(a, 0, n - 1)
BM48 数据流中的中位数
classSolution:
val = []
defInsert(self, num):
# write code hereiflen(self.val) == 0:
self.val.append(num)
else:
i = 0while i < len(self.val):
if num <= self.val[i]:
break
i = i + 1self.val.insert(i, num)
defGetMedian(self):
# write code here
n = len(self.val)
if n % 2 == 1:
returnself.val[n // 2]
else:
return (self.val[n // 2] + self.val[n // 2 - 1]) / 2.0
classSolution:
deftwoSum(self, numbers: List[int], target: int) -> List[int]:
# write code here
dic = dict()
for i, num inenumerate(numbers):
if target - num in dic:
return [dic[target - num] + 1, i + 1]
dic[num] = i
BM51 数组中出现次数超过一半的数字
from collections import Counter
classSolution:
defMoreThanHalfNum_Solution(self, numbers: List[int]) -> int:
# write code here
dic = Counter(numbers)
l = len(numbers)
for num in numbers:
if dic[num] > l / 2:
return num
BM52 数组中只出现一次的两个数字
from collections import Counter
classSolution:
defFindNumsAppearOnce(self, nums: List[int]) -> List[int]:
# write code here
dic = Counter(nums)
res = []
for num in dic:
if dic[num] == 1:
res.append(num)
returnsorted(res)
BM53 缺失的第一个正整数
classSolution:
defminNumberDisappeared(self, nums: List[int]) -> int:
# write code here
A = set()
for num in nums:
A.add(num)
i = 1whileTrue:
if i notin A:
return i
i += 1
BM54 三数之和
classSolution:
defthreeSum(self, num: List[int]) -> List[List[int]]:
# write code here
res = []
num.sort()
n = len(num)
i = 0while i < n - 2:
j = i + 1
k = n - 1while j < k:
s = num[i] + num[j] + num[k]
if s < 0:
j += 1elif s > 0:
k -= 1else:
res.append([num[i], num[j], num[k]])
j += 1
k -= 1
i += 1
res = [list(i) for i inset(tuple(i) for i in res)]
returnsorted(res)
classSolution:
defNqueen(self, n: int) -> int:
# write code heredefdfs(cols, d1, d2):
r = len(cols)
if r == n:
res.append(cols)
returnfor i inrange(n):
if i notin cols and r - i notin d1 and r + i notin d2:
dfs(cols + [i], d1 + [r - i], d2 + [r + i])
cols, d1, d2 = [], [], []
res = []
dfs(cols, d1, d2)
returnlen(res)
BM60 括号生成
classSolution:
defgenerateParenthesis(self, n: int) -> List[str]:
# write code heredefdfs(l, r, path, res):
if l > r or l < 0or r < 0:
returnif l == 0and r == 0:
res.append(path)
return
dfs(l - 1, r, path + '(', res)
dfs(l, r - 1, path + ')', res)
path, res = '', []
dfs(n, n, path, res)
return res
BM61 矩阵最长递增路径
classSolution:
defsolve(self, matrix: List[List[int]]) -> int:
# write code here
m, n = len(matrix), len(matrix[0])
mem = [[0] * n for i inrange(m)]
res = 0defdfs(i, j):
if mem[i][j] != 0:
return mem[i][j]
mem[i][j] = 1for newx, newy in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if0 <= newx < m and0 <= newy < n and matrix[newx][newy] > matrix[i][j]:
mem[i][j] = max(mem[i][j], dfs(newx, newy) + 1)
return mem[i][j]
for i inrange(m):
for j inrange(n):
dfs(i, j)
res = max(res, mem[i][j])
return res
classSolution:
defLIS(self, arr: List[int]) -> int:
# write code here
n = len(arr)
ifnot n:
return0
dp = [1] * n
for i inrange(n):
for j inrange(i):
if arr[j] < arr[i]:
dp[i] = max(dp[i], dp[j] + 1)
returnmax(dp)
BM72 连续子数组的最大和
classSolution:
defFindGreatestSumOfSubArray(self, array: List[int]) -> int:
# write code hereifnot array:
return0
n = len(array)
s, res = float('-inf'), float('-inf')
for i inrange(n):
s = max(s + array[i], array[i])
res = max(res, s)
return res
BM73 最长回文子串
classSolution:
defgetLongestPalindrome(self, A: str) -> int:
# write code heredefjudge(A, l, r):
if l > r:
return0while l >= 0and r < len(A) and A[l] == A[r]:
l -= 1
r += 1return r - l - 1
res = 1for i inrange(len(A) - 1):
len1 = judge(A, i, i)
len2 = judge(A, i, i + 1)
res = max(res, max(len1, len2))
return res
BM74 数字字符串转化成 IP 地址
classSolution:
defrestoreIpAddresses(self, s: str) -> List[str]:
# write code here
res = []
n = len(s)
i = 1while i < 4and i < n - 2:
j = i + 1while j < i + 4and j < n - 1:
k = j + 1while k < j + 4and k < n:
if n - k > 3:
k += 1continue
a = s[:i]
b = s[i:j]
c = s[j:k]
d = s[k:]
ifint(a) > 255orint(b) > 255orint(c) > 255orint(d) > 255:
k += 1continueif ((len(a) > 1andint(a[0]) == 0) or (len(b) > 1andint(b[0]) == 0) or (len(c) > 1andint(c[0]) == 0) or (len(d) > 1andint(d[0]) == 0)):
k += 1continue
res.append(a + '.' + b + '.' + c + '.' + d)
k += 1
j += 1
i += 1return res
BM75 编辑距离 (一)
classSolution:
defeditDistance(self, str1: str, str2: str) -> int:
# write code here
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for i inrange(m + 1)]
for i inrange(1, m + 1):
dp[i][0] = dp[i - 1][0] + 1for j inrange(1, n + 1):
dp[0][j] = dp[0][j - 1] + 1for i inrange(1, m + 1):
for j inrange(1, n + 1):
if str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1return dp[m][n]
BM76 正则表达式匹配
classSolution:
defmatch(self, str: str, pattern: str) -> bool:
# write code here
l = len(pattern)
if l == 0:
returnnotstrelif l == 1:
iflen(str) == l and pattern[0] in {str[0], '.'}:
returnTrueelse:
returnFalseelse:
firstmatch = strand pattern[0] in {str[0], '.'}
if pattern[1] == '*':
returnself.match(str, pattern[2:]) or firstmatch andself.match(str[1:], pattern)
else:
return firstmatch andself.match(str[1:], pattern[1:])
BM77 最长的括号子串
classSolution:
deflongestValidParentheses(self, s: str) -> int:
# write code here
st = []
start = -1
res = 0for i inrange(len(s)):
if s[i] == '(':
st.append(i)
else:
ifnot st:
start = i
else:
st.pop()
if st:
res = max(res, i - st[-1])
else:
res = max(res, i - start)
return res
BM78 打家劫舍 (一)
classSolution:
defrob(self, nums: List[int]) -> int:
# write code here
n = len(nums)
if n == 1:
return nums[0]
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i inrange(2, n):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[n - 1]
BM79 打家劫舍 (二)
classSolution:
defcaculate(self, nums):
n = len(nums)
dp = [0] * n
if n == 1:
return nums[0]
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i inrange(2, n):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[n - 1]
defrob(self, nums: List[int]) -> int:
# write code here
l1 = self.caculate(nums[:-1])
l2 = self.caculate(nums[1:])
returnmax(l1, l2)
BM80 买卖股票的最好时机 (一)
classSolution:
defmaxProfit(self, prices: List[int]) -> int:
# write code here
n = len(prices)
dp = [[0] * 2for i inrange(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i inrange(1, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])
dp[i][1] = max(dp[i - 1][1], -prices[i])
return dp[n - 1][0]
classSolution:
deflongestCommonPrefix(self, strs: List[str]) -> str:
ifnot strs:
return''for i inrange(len(strs[0])):
for s in strs[1:]:
if i >= len(s) or s[i] != strs[0][i]:
return strs[0][:i]
return strs[0]
BM85 验证 IP 地址
classSolution:
defsolve(self, IP):
# write code hereif'.'in IP:
for ip in IP.split('.'):
if ip.isdigit() isFalseor ip == ''or ip[0] == '0'or (not0 <= int(ip) <= 255):
return'Neither'return'IPv4'if':'in IP:
for ip in IP.split(':'):
if ip == ''or (len(ip) > 1andlen(ip) == ip.count('0')) ornotall(c in'0123456789abcdefABCDEF'for c in ip):
return'Neither'return'IPv6'
BM86 大数加法
classSolution:
defsolve(self, s: str, t: str) -> str:
s = [int(c) for c in s]
t = [int(c) for c in t]
res = []
digi = 1
carry = 0while s or t:
if s and t:
SUM = s.pop() + t.pop() + carry
carry = SUM // 10
s1 = SUM % 10
res.insert(0, str(s1))
elif s:
SUM = s.pop() + carry
carry = SUM // 10
s1 = SUM % 10
res.insert(0, str(s1))
else:
SUM = t.pop() + carry
carry = SUM // 10
s1 = SUM % 10
res.insert(0, str(s1))
if carry != 0:
res.insert(0, str(carry))
return''.join(res)
BM87 合并两个有序的数组
classSolution:
defmerge(self, A, m, B, n):
# write code here
i = m - 1
j = n - 1
k = m + n - 1while i >= 0and j >= 0:
if A[i] > B[j]:
A[k] = A[i]
k -= 1
i -= 1else:
A[k] = B[j]
k -= 1
j -= 1if i < 0:
while j >= 0:
A[k] = B[j]
k -= 1
j -= 1
BM88 判断是否为回文字符串
classSolution:
defjudge(self, str: str) -> bool:
# write code here
l, r = 0, len(str) - 1while l < r:
ifstr[l] == str[r]:
l += 1
r -= 1continueelse:
returnFalsereturnTrue
BM89 合并区间
classSolution:
defmerge(self, intervals: List[Interval]) -> List[Interval]:
# write code here
res = []
n = len(intervals)
if n == 0:
return res
intervals.sort(key=lambda x: x.start)
res.append(intervals[0])
for i inrange(1, n):
if res[-1].end >= intervals[i].start:
res[-1].end = max(res[-1].end, intervals[i].end)
else:
res.append(intervals[i])
return res
BM90 最小覆盖子串
classSolution:
defcheck(self, hash):
for k, v inhash.items():
if v < 0:
returnFalsereturnTruedefminWindow(self, S: str, T: str) -> str:
# write code here
res = len(S) + 1hash = dict()
for c in T:
if c inhash:
hash[c] -= 1else:
hash[c] = -1
l, r = 0, 0
cnt = len(S) + 1
left, right = -1, -1while r < len(S):
c = S[r]
if c inhash:
hash[c] += 1whileself.check(hash):
if cnt > r - l + 1:
cnt = r - l + 1
left = l
right = r
t = S[l]
if t inhash:
hash[S[l]] -= 1
l += 1
r += 1if left == -1:
return""return S[left:right + 1]
classSolution:
defmaxLength(self, arr: List[int]) -> int:
# write code here
l, r = 0, 0hash = dict()
res = 0while r < len(arr):
if arr[r] inhash:
hash[arr[r]] += 1else:
hash[arr[r]] = 1whilehash[arr[r]] > 1:
hash[arr[l]] -= 1
l += 1
res = max(res, r - l + 1)
r += 1return res
BM93 盛水最多的容器
classSolution:
defmaxArea(self, height: List[int]) -> int:
# write code here
n = len(height)
if n < 2:
return0
l, r = 0, n - 1
res = 0while l < r:
temp = min(height[l], height[r]) * (r - l)
res = max(res, temp)
if height[l] < height[r]:
l += 1else:
r -= 1return res
BM94 接雨水问题
classSolution:
defmaxWater(self, arr: List[int]) -> int:
# write code here
n = len(arr)
if n <= 2:
return0
l, r = 0, n - 1
maxl, maxr = -1, -1
res = 0while l < r:
maxl = max(maxl, arr[l])
maxr = max(maxr, arr[r])
if maxl < maxr:
res += maxl - arr[l]
l += 1else:
res += maxr - arr[r]
r -= 1return res
BM95 分糖果问题
classSolution:
defcandy(self, arr: List[int]) -> int:
# write code here
n = len(arr)
sweet = [1] * len(arr)
for i inrange(1, n):
if arr[i] > arr[i - 1]:
sweet[i] = sweet[i - 1] + 1for i inrange(n - 2, -1, -1):
if arr[i] > arr[i + 1] and sweet[i] <= sweet[i + 1]:
sweet[i] = sweet[i + 1] + 1returnsum(sweet)
BM96 主持人调度(二)
classSolution:
defminmumNumberOfHost(self, n: int, startEnd: List[List[int]]) -> int:
# write code here
start, end = list(), list()
for i inrange(len(startEnd)):
start.append(startEnd[i][0])
end.append(startEnd[i][1])
start.sort()
end.sort()
i, j, res = 0, 0, 0for i inrange(len(start)):
if start[i] >= end[j]:
j += 1else:
res += 1return res
classSolution:
defspiralOrder(self, matrix: List[List[int]]) -> List[int]:
# write code here
res = list()
while matrix:
res += matrix.pop(0)
matrix = list(zip(*matrix))[::-1]
return res
BM99 顺时针旋转矩阵
classSolution:
defrotateMatrix(self, mat: List[List[int]], n: int) -> List[List[int]]:
# write code herefor i inrange(n):
for j inrange(i):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
for i inrange(n):
mat[i].reverse()
return mat
BM100 设计 LRU 缓存结构
classListNode:
def__init__(self, val):
self.val = val
self.next = Noneself.pre = NoneclassSolution:
def__init__(self, capacity: int):
# write code hereself.cap = capacity
self.hash = dict()
self.head = Noneself.tail = Nonedefget(self, key: int) -> int:
# write code hereif key inself.hash:
ifself.hash[key].pre != None:
self.freshListNode(self.hash[key])
returnself.hash[key].val[0]
else:
return -1defset(self, key: int, value: int) -> None:
# write code here
value = [value, key]
if key inself.hash:
self.hash[key].val = value
ifself.hash[key].pre != None:
self.freshListNode(self.hash[key])
returnifself.cap > 0:
ele = ListNode(value)
self.hash[key] = ele
self.addOneNode(ele)
self.cap -= 1else:
delself.hash[self.tail.val[1]]
self.hash[key] = self.tail
self.tail.val = value
ifself.tail.pre != None:
self.freshListNode(self.tail)
deffreshListNode(self, ele):
ele.pre.next = ele.nextifself.tail == ele:
self.tail = ele.pre
else:
ele.next.pre = ele.pre
ele.pre = Noneself.head.pre = ele
ele.next = self.head
self.head = ele
defaddOneNode(self, ele):
ifself.head == None:
self.head = ele
self.tail = ele
else:
ele.pre = None
ele.next = self.head
self.head.pre = ele
self.head = ele
# Your Solution object will be instantiated and called as such:# solution = Solution(capacity)# output = solution.get(key)# solution.set(key,value)