classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: j = -1 for i inrange(1,len(nums)): temp=nums[:i] if target-nums[i] in temp: j = temp.index(target-nums[i]) break if j >=0: return [j, i]
3.无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: deflengthOfLongestSubstring(self, s: str) -> int: max_len, hashmap=0,{} start =0 for end inrange(len(s)): hashmap[s[end]] = hashmap.get(s[end],0) + 1 iflen(hashmap) == end-start +1: max_len = max(max_len, end-start+1) while end-start+1 >len(hashmap): hashmap[s[start]] -=1 if hashmap[s[start]]==0: del hashmap[s[start]] start += 1 return max_len
11.盛最多水的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 返回容器可以储存的最大水量。 说明:你不能倾斜容器。
1 2 3 4 5 6 7 8 9 10 11
class Solution: def maxArea(self, height: List[int]) -> int: i, j, res = 0, len(height)-1, 0 while i<j: if height[i]<=height[j]: res = max(res, height[i]*(j-i)) i += 1 elif height[i]>height[j]: res = max(res, height[j]*(j-i)) j -= 1 return res
classSolution: defthreeSum(self, nums: [int]) -> [[int]]: nums.sort() res, k = [], 0 for k inrange(len(nums) - 2): if nums[k] > 0: break# 1. because of j > i > k. if k > 0and nums[k] == nums[k - 1]: continue# 2. skip the same `nums[k]`. i, j = k + 1, len(nums) - 1 while i < j: # 3. double pointer s = nums[k] + nums[i] + nums[j] if s < 0: i += 1 while i < j and nums[i] == nums[i - 1]: i += 1 elif s > 0: j -= 1 while i < j and nums[j] == nums[j + 1]: j -= 1 else: res.append([nums[k], nums[i], nums[j]]) i += 1 j -= 1 while i < j and nums[i] == nums[i - 1]: i += 1 while i < j and nums[j] == nums[j + 1]: j -= 1 return res
classSolution: defisValid(self, s: str) -> bool: # dic = {'{':'}','[':']','(':')'} dic = {')':'(',']':'[','}':'{'} stack = [] for i in s: if stack and i in dic: if stack[-1] == dic[i]: stack.pop() else: returnFalse else: stack.append(i) returnnot stack
# class Solution: # def isValid(self, s: str) -> bool: # dic = {')':'(',']':'[','}':'{'} # stack = [] # for i in s: # if stack and i in dic: # if stack[-1] == dic[i]: stack.pop() # else: return False # else: stack.append(i) # return not stack
21.合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defmergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: ifnot l1: return l2 # 终止条件,直到两个链表都空 ifnot l2: return l1
classSolution: defsearchRange(self, nums: List[int], target: int) -> List[int]: defbinarySearchLeft(nums:List[int], target:int)->List[int]: l = -1 r = len(nums) while l+1 != r : mid = l+(r-l)//2 if nums[mid] >= target : r = mid else : l = mid return r defbinarySearchRight(nums:List[int], target:int)->List[int]: l = -1 r = len(nums) while l+1 != r : mid = l+(r-l)//2 if nums[mid] <= target : l = mid else : r = mid return l leftIdx = binarySearchLeft(nums, target) rightIdx = binarySearchRight(nums, target)
if leftIdx<=rightIdx and rightIdx<len(nums) and nums[leftIdx]==target and nums[rightIdx]==target : return [leftIdx, rightIdx]
classSolution: defisValidSudoku(self, board: List[List[str]]) -> bool: row, col, sqrt = defaultdict(set), defaultdict(set), defaultdict(set) for i inrange(9): for j inrange(9): val = board[i][j] if val == '.': continue point = i // 3 * 3 + j // 3 print(point) if val in row[i] or val in col[j] or val in sqrt[point]: print(i, j, val) print(row, col, sqrt) returnFalse row[i].add(val) col[j].add(val) sqrt[point].add(val) returnTrue
classSolution(object): defmaxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ res = [nums[0],] for i inrange(1,len(nums)): res.append(max(res[i-1]+nums[i],nums[i])) returnmax(res)
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。 由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。 注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmySqrt(self, x: int) -> int: if x <= 1: return x x_2 = x // 2 for i inrange(x_2+1): if i * i == x: return i elif i * i > x: return i-1 return x_2
70.爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
1 2 3 4 5 6 7 8 9
classSolution: defclimbStairs(self, n: int) -> int: s = [1, 2] if n <= 2: return s[n - 1] whilelen(s) < n: print(s) s.append(s[-1] + s[-2]) return s[-1]
73.矩阵置零
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defsetZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ row = len(matrix) col = len(matrix[0]) row_zero = set() col_zero = set() for i inrange(row): for j inrange(col): if matrix[i][j] == 0: row_zero.add(i) col_zero.add(j) for i inrange(row): for j inrange(col): if i in row_zero or j in col_zero: matrix[i][j] = 0
74.搜索二维矩阵
给你一个满足下述两条属性的 m x n 整数矩阵: 每行中的整数从左到右按非递减顺序排列。 每行的第一个整数大于前一行的最后一个整数。 给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defsearchMatrix(self, matrix: List[List[int]], target: int) -> bool: nums = [] for list_ in matrix: nums += list_ low = 0 high = len(nums)-1 while low <= high: mid = (low + high) guess = nums[mid] if guess == target: returnTrue if guess > target: high = mid - 1 else: low = mid + 1 returnFalse
77.组合
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回答案。
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defdeleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: cur = head if head isNone: returnNone while cur.next: if cur.val == cur.next.val: cur.next = cur.next.next else: cur =cur.next return head
# class Solution: # def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: # if head is None: # return None # cur = head # while cur.next: # if cur.next.val == cur.val: # cur.next = cur.next.next # else: # cur = cur.next # return head
88.合并两个有序数组
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。 请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。 注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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 classSolution: defisSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: ifnot p andnot q: returnTrue elif p and q: return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) else: returnFalse
# 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 classSolution: defminDepth(self, root: Optional[TreeNode]) -> int: defmin_tree_depth(r): if r == None: return0 l = min_tree_depth(r.left) right = min_tree_depth(r.right) if l == 0or right == 0: returnmax(l, right) + 1 else: returnmin(l, right) + 1
return min_tree_depth(root)
116.填充每个节点的下一个右侧节点指针
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL
defBFS(oneLayer): nextLayer = [] # 每一次都搞个空的列表,去建立nextLayer for i in oneLayer: if i.left: nextLayer.append(i.left) if i.right: nextLayer.append(i.right)
defBFS(oneLayer): nextLayer = [] # 每一次都搞个空的列表,去建立nextLayer for i in oneLayer: if i.left: nextLayer.append(i.left) if i.right: nextLayer.append(i.right)
classSolution: defgenerate(self, numRows: int) -> List[List[int]]: res = [[1]*i for i inrange(1, numRows+1)] for index, element inenumerate(res): for j inrange(1, len(element)-1): element[j] = res[index-1][j-1] + res[index-1][j]
return res
120.三角形最小路径和
给定一个三角形 triangle ,找出自顶向下的最小路径和。 每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。也就是说,如果正位于当前行的下标 i ,那么下一步可以移动到下一行的下标 i 或 i + 1 。
1 2 3 4 5 6
classSolution: defminimumTotal(self, triangle: List[List[int]]) -> int: for i inrange(len(triangle)-2,-1,-1): for j inrange(len(triangle[i])): triangle[i][j] = triangle[i][j] + min(triangle[i+1][j], triangle[i+1][j+1]) return triangle[0][0]
121.买卖股票的最佳时机
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
classSolution: deflongestConsecutive(self, nums: List[int]) -> int: res=0 num_set = set(nums) for num in num_set: if (num-1) notin num_set: seq_len = 1 while (num+1) in num_set: seq_len += 1 num += 1 res = max(res, seq_len) return res
classSolution: defsingleNumber(self, nums: List[int]) -> int: for i in nums: n = nums.count(i) if n==1: return i else: continue
141.环形链表
给你一个链表的头节点 head ,判断链表中是否有环。 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。 如果链表中存在环 ,则返回 true 。 否则,返回 false 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: Optional[ListNode]) -> bool: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if fast is slow: returnTrue returnFalse
142.环形链表II
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。 不允许修改 链表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution(object): defdetectCycle(self, head): fast, slow = head, head whileTrue: ifnot (fast and fast.next): return fast, slow = fast.next.next, slow.next if fast == slow: break fast = head while fast != slow: fast, slow = fast.next, slow.next return fast
classSolution: defmajorityElement(self, nums: List[int]) -> int: count_dict={} # length = len(nums)//2 for num inlist(set(nums)): count_dict[num] = nums.count(num) # res = [k for k, v in count_dict.items() if v >= length] returnmax(count_dict, key=lambda x: count_dict[x])
175.组合两个表
表: Person +————-+———+ | 列名 | 类型 | +————-+———+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +————-+———+ personId 是该表的主键(具有唯一值的列)。 该表包含一些人的 ID 和他们的姓和名的信息。
1 2 3
# Write your MySQL query statement below select firstName ,lastName ,city ,state from Person t1 left join Address t2 on t1.PersonId=t2.PersonId
176.第二高的薪水
Employee 表: +————-+——+ | Column Name | Type | +————-+——+ | id | int | | salary | int | +————-+——+ 在 SQL 中,id 是这个表的主键。 表的每一行包含员工的工资信息。 查询并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null(Pandas 则返回 None) 。
1 2 3 4 5 6 7 8
# Write your MySQL query statement below select ( select salary from ( select salary, dense_rank() over (orderby salary desc) rn from Employee ) t where t.rn=2 limit 1 ) SecondHighestSalary;
# Read from the file file.txt and output all valid phone numbers to stdout. python3 -c "import re;lines=open('file.txt').readlines();lines=[i.strip()for i in lines];ans=[i for i in lines if re.match('^\(\d{3}\) \d{3}-\d{4}$',i) or re.match('^\d{3}-\d{3}-\d{4}$',i)]; print('\n'.join(ans))"
196.删除重复的电子邮箱
表: Person +————-+———+ | Column Name | Type | +————-+———+ | id | int | | email | varchar | +————-+———+ id 是该表的主键列(具有唯一值的列)。 该表的每一行包含一封电子邮件。电子邮件将不包含大写字母。 编写解决方案 删除 所有重复的电子邮件,只保留一个具有最小 id 的唯一电子邮件。 (对于 SQL 用户,请注意你应该编写一个 DELETE 语句而不是 SELECT 语句。) (对于 Pandas 用户,请注意你应该直接修改 Person 表。) 运行脚本后,显示的答案是 Person 表。驱动程序将首先编译并运行您的代码片段,然后再显示 Person 表。Person 表的最终顺序 无关紧要 。 返回结果格式如下示例所示。
1 2 3 4 5 6
# Please write a DELETE statement and DO NOT write a SELECT statement. # Write your MySQL query statement below DELETE p1 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id
class Solution: def numIslands(self, grid: List[List[str]]) -> int: def dfs(grid,r,c): if not 0<=r<len(grid) or not 0<=c<len(grid[0]):return if grid[r][c]!="1":return #注意题目这里输入的是字符"0",“1” grid[r][c]="2" dfs(grid,r-1,c) dfs(grid,r+1,c) dfs(grid,r,c-1) dfs(grid,r,c+1) return 1 #是岛屿,则返回1
res=0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c]=="1": res+=dfs(grid,r,c) #累加岛屿的数量 return res
205.同构字符串
给定两个字符串 s 和 t ,判断它们是否是同构的。 如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。 每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。
1 2 3 4 5 6 7 8 9
classSolution: defisIsomorphic(self, s: str, t: str) -> bool: # return all(s.index(s[i]) == t.index(t[i]) for i in range(len(s))) for i inrange(len(s)): if s.index(s[i]) == t.index(t[i]): continue else: returnFalse returnTrue
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: # def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # prev, curr = None, head # while curr is not None: # next = curr.next # curr.next = prev # prev = curr # curr = next # return prev
defreverseList(self, head: ListNode) -> ListNode: if head isNoneor head.nextisNone: return head p = self.reverseList(head.next) head.next.next = head head.next = None
给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。
1 2 3 4 5 6 7 8 9 10 11 12
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: list_dict = {} for i in range(len(nums)): if nums[i] not in list_dict: list_dict[nums[i]]=i else: if i- list_dict[nums[i]] <=k: return True else : list_dict[nums[i]] = i return False
231.2的幂
给你一个整数 n,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。 如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。
1 2 3
classSolution: defisPowerOfTwo(self, n: int) -> bool: return n > 0and n & (n - 1) == 0
258.各位相加
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。
1 2 3 4 5
classSolution: defaddDigits(self, num: int) -> int: whilelen(str(num)) >= 2: num = sum(int(i) for i inlist(str(num))) return num
263.丑数
丑数 就是只包含质因数 2、3 和 5 的正整数。 给你一个整数 n ,请你判断 n 是否为 丑数 。如果是,返回 true ;否则,返回 false
1 2 3 4 5 6 7 8 9 10 11
class Solution: def isUgly(self, n: int) -> bool: if n <=0: return False while n % 2 == 0 : n //= 2 while n % 3 == 0 : n //= 3 while n % 5 == 0 : n //= 5 return n ==1
classSolution: defintersect(self, nums1: List[int], nums2: List[int]) -> List[int]: jiaoji = set(nums1) & set(nums2) res = [] for i in jiaoji: res += [i] * min(nums1.count(i), nums2.count(i)) return res
classSolution: deffirstUniqChar(self, s: str) -> int: # list_ = list(s) # cnt = {} # for c in list_: # cnt[c] = list_.count(c) # for key,vaule in cnt.items(): # if vaule == 1: # return list_.index(key) # return -1
m = {} l_s = list(s) for word in l_s: m[word] = 0 for word in l_s: m[word] += 1 for key,vaule in m.items(): if vaule == 1: return l_s.index(key) return -1
389.找不同
给定两个字符串 s 和 t ,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。
classSolution: defupdateMatrix(self, mat: List[List[int]]) -> List[List[int]]: m, n = len(mat), len(mat and mat[0]) dir = [(-1,0), (0,1), (1,0), (0,-1)]
queue = deque() for r inrange(m): for c inrange(n): if mat[r][c] == 0: queue.append((r, c)) else: mat[r][c] = -1
while queue: r, c = queue.popleft() for dr,dc indir: nr, nc = r + dr, c + dc if nr < 0or nr >= m or nc < 0or nc >= n or mat[nr][nc] != -1: continue mat[nr][nc] = mat[r][c] + 1 queue.append((nr, nc)) return mat
547.省份数量
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。 省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。 给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。 返回矩阵中 省份 的数量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: def dfs(i: int): for j in range(cities): if isConnected[i][j] == 1 and j not in visited: visited.add(j) dfs(j)
cities = len(isConnected) visited = set() provinces = 0
for i in range(cities): if i not in visited: dfs(i) provinces += 1
return provinces
566.重塑矩阵
在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。 给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。 重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。 如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmatrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: iflen(mat) * len(mat[0]) != r * c: return mat res, stack = [], [] for row in mat: for e in row: stack.append(e) iflen(stack) == c: res.append(stack) stack = [] return res
classSolution: defcheckInclusion(self, s1: str, s2: str) -> bool: hashmap1, hashmap2, result = {}, {}, False for char in s1: hashmap1[char] = hashmap1.get(char, 0) + 1
start = 0 for end inrange(len(s2)): hashmap2[s2[end]] = hashmap2.get(s2[end], 0) + 1 if hashmap2 == hashmap1: result = True
if end >= len(s1) - 1: hashmap2[s2[start]] -= 1 if hashmap2[s2[start]] == 0: del hashmap2[s2[start]] start += 1
return result
572.另一棵树的子树
给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。 二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ if not s and not t: return True if not s or not t: return False return self.isSameTree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSameTree(self, s, t): if not s and not t: return True if not s or not t: return False return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)
class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: res = [] for i in range(left,right+1): for j in str(i): if j=='0' or i % int(j)!=0: break else: res.append(i) return res
733.图像渲染
有一幅以 m x n 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。 你也被给予三个整数 sr , sc 和 newColor 。你应该从像素 image[sr][sc] 开始对图像进行 上色填充 。 为了完成 上色工作 ,从初始像素开始,记录初始坐标的 上下左右四个方向上 像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应 四个方向上 像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为 newColor 。 最后返回 经过上色渲染后的图像 。
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: stack, res = [], [0]* len(temperatures) for i , num in enumerate(temperatures): while stack and temperatures[stack[-1]]< num: index = stack.pop() res[index] = i - index stack.append(i) return res
class Solution: def numJewelsInStones(self, jewels, stones): J = [j for j in jewels] S = [s for s in stones] res = 0 for i in range(len(J)): res += S.count(J[i]) return res
784.字母大小全排列
给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。 返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。
1 2 3 4 5 6 7 8 9
classSolution: defletterCasePermutation(self, s: str) -> List[str]: ans = [""] for i, c inenumerate(s): if c.isalpha(): ans = [a + c.lower() for a in ans] + [a + c.upper() for a in ans] else: ans = [a + c for a in ans] return ans
796.旋转字符串
给定两个字符串, s 和 goal。如果在若干次旋转操作之后,s 能变成 goal ,那么返回 true 。 s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 例如, 若 s = ‘abcde’,在旋转一次之后结果就是’bcdea’ 。
1 2 3 4 5 6 7 8 9 10
classSolution: defrotateString(self, s: str, goal: str) -> bool: length = len(s) i = 0 while i <= length: s = s[1:]+s[0] if s == goal: returnTrue i+=1 returnFalse
844. 比较含退格的字符串
给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。 注意:如果对空文本输入退格字符,文本继续为空。 示例 1: 输入:s = “ab#c”, t = “ad#c” 输出:true 解释:s 和 t 都会变成 “ac”。
1 2 3 4 5 6 7 8 9 10 11 12 13
class Solution: def backspaceCompare(self, s: str, t: str) -> bool: def remove_(str_): r = [] for i in range(len(str_)): if str_[i] != '#': r.append(str_[i]) elif str_[i] == '#' and len(r)>=1: r.pop()
return r
return remove_(s) ==remove_(t)
944.腐烂的橘子
在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一: 值 0 代表空单元格; 值 1 代表新鲜橘子; 值 2 代表腐烂的橘子。 每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。 返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: deforangesRotting(self, grid: List[List[int]]) -> int: row = len(grid) col = len(grid[0]) rotten = {(i, j) for i inrange(row) for j inrange(col) if grid[i][j] == 2} # 腐烂集合 fresh = {(i, j) for i inrange(row) for j inrange(col) if grid[i][j] == 1} # 新鲜集合 time = 0 while fresh: ifnot rotten: return -1 # 即将腐烂的如果在新鲜的集合中,就将它腐烂 rotten = {(i + di, j + dj) for i, j in rotten for di, dj in [(0, 1), (0, -1), (1, 0), (-1, 0)] if (i + di, j + dj) in fresh} fresh -= rotten # 剔除腐烂的 time += 1 return time
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: res=[] n,m=len(firstList),len(secondList) i,j=0,0 while i<n and j<m: left = max(firstList[i][0],secondList[j][0]) right = min(firstList[i][1],secondList[j][1]) if left <= right: #判断是否有交集的条件 res.append([left,right]) if firstList[i][1]<secondList[j][1]: #哪个右区间元素较小,指针就向前移动一位 i+=1 else:e j+=1 return res
1021.删除最外层的括号
有效括号字符串为空 “”、”(“ + A + “)” 或 A + B ,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。 例如,””,”()”,”(())()” 和 “(()(()))” 都是有效的括号字符串。 如果有效字符串 s 非空,且不存在将其拆分为 s = A + B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。 给出一个非空有效字符串 s,考虑将其进行原语化分解,使得:s = P_1 + P_2 + … + P_k,其中 P_i 是有效括号字符串原语。 对 s 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 s 。
1 2 3 4 5 6 7 8 9
classSolution: defremoveOuterParentheses(self, S: str) -> str: m, j, re = 0, 0, str() for i inrange(len(S)): m += 1if S[i]=='('else -1 ifnot m: re += S[j+1:i] j = i + 1 return re
classSolution: defminTimeToVisitAllPoints(self, points: List[List[int]]) -> int: total = 0 for i inrange(1,len(points)): a = abs(points[i][0]-points[i-1][0]) b = abs(points[i][1]-points[i-1][1]) t = max(a,b) total += t return total
1281.整数的各位积和之差
给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defsubtractProductAndSum(self, n): returneval("*".join(str(n))) - eval("+".join(str(n))) # n = list(str(n)) # muti = 1 # summ = 0 # for i in n: # muti *= int(i) # summ += int(i) # return muti-summ
1295.统计位数为偶数的数字
给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。
1 2 3 4 5 6 7 8
class Solution: def findNumbers(self, nums: List[int]) -> int: # res = 0 # for num in nums: # if len(str(num)) %2 == 0: # res +=1 # return res return sum(map(lambda x: len(str(x)) & 1 ^ 1, nums))
1342.将数字变成0的操作次数
给你一个非负整数 num ,请你返回将它变成 0 所需要的步数。 如果当前数字是偶数,你需要把它除以 2 ;否则,减去 1 。
1 2 3 4 5 6 7 8 9 10 11
classSolution: defnumberOfSteps(self, num: int) -> int: flag = 0 while num != 0: if num%2 == 0: num = num/2 flag += 1 else: num = num - 1 flag += 1 return flag
classSolution: defsmallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: nums_ = sorted(nums) res = [] for i in nums: res.append(nums_.index(i)) return res
import numpy as np classSolution: defdiagonalSum(self, mat: List[List[int]]) -> int: mat = np.array(mat) for i inrange(mat.shape[0]): for j inrange(mat.shape[1]): if i != j and i + j + 1 != mat.shape[0]: mat[i, j] = 0 returnint(np.sum(mat))
defaddCar(self, carType: int) -> bool: if self.bucket[carType] > 0: self.bucket[carType] -= 1 returnTrue returnFalse # Your ParkingSystem object will be instantiated and called as such: # obj = ParkingSystem(big, medium, small) # param_1 = obj.addCar(carType)
1614.括号的最大嵌套深度
如果字符串满足以下条件之一,则可以称之为 有效括号字符串(valid parentheses string,可以简写为 VPS): 字符串是一个空字符串 “”,或者是一个不为 “(“ 或 “)” 的单字符。 字符串可以写为 AB(A 与 B 字符串连接),其中 A 和 B 都是 有效括号字符串 。 字符串可以写为 (A),其中 A 是一个 有效括号字符串 。 类似地,可以定义任何有效括号字符串 S 的 嵌套深度 depth(S): depth(“”) = 0 depth(C) = 0,其中 C 是单个字符的字符串,且该字符不是 “(“ 或者 “)” depth(A + B) = max(depth(A), depth(B)),其中 A 和 B 都是 有效括号字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defmaxDepth(self, s): if'('and')'notinlist(s): return0 dep,m = [],0 for st in s: if st == '(' : m += 1 dep.append(m) if st == ')' : m -= 1 dep.append(m) returnmax(dep) # try : # return max(dep) # except: # return 0
给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。 请你返回 words 数组中 一致字符串 的数目。
1 2 3 4 5 6 7 8 9
classSolution: defcountConsistentStrings(self, allowed: str, words: List[str]) -> int: num_result = len(words) #默认都是 for word in words: for a_char in word: if allowed.find(a_char)==-1: num_result-=1#一个字母不在allowed里面 就减去 break return num_result
1695.删除子数组的最大得分
给你一个正整数数组 nums ,请你从中删除一个含有 若干不同元素 的子数组。删除子数组的 得分 就是子数组各元素之 和 。 返回 只删除一个 子数组可获得的 最大得分 。 如果数组 b 是数组 a 的一个连续子序列,即如果它等于 a[l],a[l+1],…,a[r] ,那么它就是 a 的一个子数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: sum_,max_sum, hashmap=0, 0, {} start = 0 for end in range(len(nums)): sum_ += nums[end] hashmap[nums[end]] = hashmap.get(nums[end], 0) + 1 if hashmap.get(nums[end], 0) < 2: max_sum = max(max_sum, sum_) while hashmap[nums[end]]>=2: head = nums[start] sum_ -= head hashmap[head] -= 1 if hashmap[head] ==0: del hashmap[head] start += 1 return max_sum
classSolution(object): defcountMatches(self, items, ruleKey, ruleValue): """ :type items: List[List[str]] :type ruleKey: str :type ruleValue: str :rtype: int """ rule = { "type":0, "color":1, "name":2} i = 0 for item in items: if item[rule[ruleKey]] == ruleValue: i +=1 return i
1822.数组元素积的符号
已知函数 signFunc(x) 将会根据 x 的正负返回特定值: 如果 x 是正数,返回 1 。 如果 x 是负数,返回 -1 。 如果 x 是等于 0 ,返回 0 。 给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。 返回 signFunc(product) 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defarraySign(self, nums): """ :type nums: List[int] :rtype: int """ num = 1 for i in nums: num *= i if0in nums: return0 elif num >0: return1 elif num <0: return -1
classSolution: defminOperations(self, nums): length = len(nums) if length <= 1: return0 ret = 0 left = nums[0] for right in nums[1:]: tmp = max(left + 1, right) ret += tmp - right left = tmp return ret
classSolution: defspiralOrder(self, matrix:[[int]]) -> [int]: ifnot matrix: return [] l, r, t, b, res = 0, len(matrix[0]) - 1, 0, len(matrix) - 1, [] whileTrue: for i inrange(l, r + 1): res.append(matrix[t][i]) # left to right t += 1 if t > b: break for i inrange(t, b + 1): res.append(matrix[i][r]) # top to bottom r -= 1 if l > r: break for i inrange(r, l - 1, -1): res.append(matrix[b][i]) # right to left b -= 1 if t > b: break for i inrange(b, t - 1, -1): res.append(matrix[i][l]) # bottom to top l += 1 if l > r: break return res
def__init__(self): """ initialize your data structure here. """ self.stack = [] self.minStack = []
defpush(self, x: int) -> None: self.stack.append(x) if self.minStack == [] or x < self.min(): self.minStack.append(x) else: temp = self.min() self.minStack.append(temp)
defpop(self) -> None: if self.stack == [] or self.minStack == []: returnNone self.minStack.pop() self.stack.pop()
deftop(self) -> int: return self.stack[-1]
defmin(self) -> int: return self.minStack[-1]
# Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.min()
classSolution: defgame(self, guess: List[int], answer: List[int]) -> int: res = 0 for i inrange(len(guess)): if guess[i] == answer[i]: res += 1 else: res += 0 return res
LCP06.拿硬币
桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。
1 2 3
classSolution: defminCount(self, coins: List[int]) -> int: returnsum([int(i/2) + i%2for i in coins])