从简单难度、最新的题目开始,前期每天两道题,希望能坚持下去,提高代码能力!
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
class Solution:
def majorityElement(self,nums):
nums.sort()
return(nums[len(nums)//2])
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
示例 2:
输入: 28
输出: "AB"
示例 3:
输入: 701
输出: "ZY"
class Solution:
def convertToTitle(self,num):
if num<=0:
return None
numA=ord('A')
if num<=26:
return chr(numA+num-1)
else:
return self.convertToTitle((num-1)//26)+chr(numA+(num-1)%26)
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
class Solution:
def twoSum(self,numbers, target):
output = []
i,j = 0,len(numbers)-1
while(i
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
示例 2:
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
示例 3:
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。
注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
#第一步判断链表是否为空
if headA==None or headB==None:
return None
#第二步找长度差
hA = headA
lenA = 0
while hA:
lenA += 1
hA = hA.next
hB = headB
lenB = 0
while hB:
lenB += 1
hB = hB.next
#确保A是长链 B是短链
if lenAlenB:
headA = headA.next
lenA -= 1
#第四步 开始比较val+next都要相同才行
while headA:
if headA==headB:
return headA
else:
headA, headB = headA.next,headB.next
return None
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# class Solution(object):
# def singleNumber(self, nums):
# set1 = set(nums)
# for num in set1:
# if nums.count(num) == 1:
# return num
# """
# :type nums: List[int]
# :rtype: int
# """
class Solution(object):
# 可用count(num)查找列表nums中单个元素num在列表nums中的个数情况
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_dict = {}
for num in nums:
nums_dict[num] = nums_dict.get(num, 0) + 1
for key, val in nums_dict.items():
if val == 1:
return key
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
#判断是否有环 设置快慢指针 且判断环的位置
if head == None or head.next == None:
return False
quick = head
slow = head
while (quick and quick.next):
if quick.next.next == slow.next:
return True
quick = quick.next.next
slow = slow.next
return False
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
str1 = []
for i in range(len(s)):
if s[i].isalnum():
str1.append(s[i])
# return str1
if len(str1) == 0:
return True
i = 0
j = len(str1)-1
while(i<=j):
if str1[i] != str1[j]:
return False
else:
i+=1
j-=1
return True
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
示例 2:
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = 0
for i in range(len(prices) - 1):
max_profit += max(0,prices[i+1] - prices[i])
return max_profit
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if(len(prices) == 0):
return 0
max_profit = 0
min_price = prices[0]
for i in range(1,len(prices)):
if prices[i]max_profit:
max_profit = prices[i] - min_price
return max_profit
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for i in range(1,rowIndex+1):
row.insert(0,0)
for j in range(i):
row[j] = row[j]+row[j+1]
return row
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
r = [1]
output = []
for i in range(1,numRows+1):
tmp = r
output.append(tuple(r))
r.insert(0,0)
for j in range(i):
r[j] = r[j] +r[j+1]
return output
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root == None:
return False
if root.left == None and root.right == None and root.val == sum:
return True
else:
return self.hasPathSum(root.left,sum - root.val) or self.hasPathSum(root.right, sum-root.val)
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
if root.left == None and root.right == None:
return 1
elif root.right == None:
return 1+self.minDepth(root.left)
elif root.left == None:
return 1+self.minDepth(root.right)
return min(1+ self.minDepth(root.right),1+ self.minDepth(root.left))
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
elif root.right == None and root.left == None:
return 1
elif root.right == None:
return 1+self.maxDepth(root.left)
elif root.left ==None:
return 1+self.maxDepth(root.right)
return max(1+self.maxDepth(root.left),1+self.maxDepth(root.right))
def isBalanced(self, root):
if not root:
return True
return abs(self.height(root.right)-self.height(root.left))<2 and self.isBalanced(root.left) and self.isBalanced(root.right)
# 求高度
def height(self, node):
if not node:
return 0
return 1+max(self.height(node.right),self.height(node.left))
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums):
num = len(nums)
if num == 0:
return
middle = nums[num // 2]
root = TreeNode(middle)
root.left = self.sortedArrayToBST(nums[:(num//2)])
root.right = self.sortedArrayToBST(nums[(num//2)+1:])
return root
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrderBottom(self, root):
#宽度优先搜索
result = []
if root is None:
return result
#1. 创建队列
queue = []
queue.append(root)
#2.while循环,队列不为空时,层次遍历
while queue:
size = len(queue)
level = []
for i in range(size):
node = queue.pop(0)
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
result.reverse()
return result
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
if not root or root.left is root.right: return True
l, r, i, o = root.left, root.right, TreeNode(0), TreeNode(0)
if (l and l.val) != (r and r.val): return False
i.left, i.right, o.left, o.right = l.left, r.right, l.right, r.left
return self.isSymmetric(i) and self.isSymmetric(o)
#递归
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root):
ans = []
def r(root):
if root == None:
return
r(root.left)
ans.append(root.val)
r(root.right)
r(root)
return ans
#迭代
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
list = []
if root is None: #基准条件
return []
list += self. inorderTraversal(root.left) #先把左节点加入
list.append(root.val) #添加根节点
list += self. inorderTraversal(root.right)#添加右节点
return list
class Solution:
def isSameTree(self, p, q):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
# if p.left == q.left and q.left == q.left:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
nums1[m:] = nums2
nums1.sort()
return nums1
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
output = 0
for i in range(len(J)):
output += S.count(J[i])
return output
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
address = address.split('.')
address = '[.]'.join(address)
return address
PS:炫耀一下
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
p1 = node
p1.val = p1.next.val
p1.next = p1.next.next
这个问题唯一的难点在于无法得知node的前节点,解决办法是复制node的next节点值 让node指向下下节点
class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
output = 0
if root == None:
return 0
if root.valR:
return self.rangeSumBST(root.left,L,R)
return root.val+self.rangeSumBST(root.left,L,R)+self.rangeSumBST(root.right,L,R)
# Write your MySQL query statement below
select name,population,area from World
where area>3000000 or population>25000000
看到这里突然想起了本科数据库学到的SQL语句,其中的Having与Group by语句,当时就没怎么明白,现在来回顾一下:
在介绍GROUP BY 和 HAVING 子句前,我们必需先讲讲SQL语言中一种特殊的函数:聚合函数,
例如SUM, COUNT, MAX, AVG等。这些函数和其它函数的根本区别就是它们一般作用在多条记录上。
having是分组(group by)后的筛选条件,分组后的数据组内再筛选
class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
#原语化分解
flag = 0
pos = 0
output = ''
for i in range(len(S)):
if S[i] == "(":
flag += 1
elif S[i] == ")":
flag -= 1
if flag == 0:
output += (S[pos+1:i])
pos = i+1
return output
class Solution(object):
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
class Solution(object):
def game(self, guess, answer):
"""
:type guess: List[int]
:type answer: List[int]
:rtype: int
"""
bingo = 0
for i in range(len(self)):
if guess[i] == answer[i]:
bingo += 1
return bingo
解答:
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def isSort(strInput):
for i in range(len(strInput)-1):
if strInput[i]>strInput[i+1]:
return False
return True
if isSort(nums):
return True
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
# del nums[i]
# if isSort(nums):
# return True
# else:
# return False
return isSort(nums[:i]+nums[i+1:]) or isSort(nums[:i+1]+nums[i+2:])
思路:如果遇到不符合条件的元素,就把这个元素去掉,去掉之后看是否符合,或者让这个元素和前面的元素相等,看这样是否符合条件。
题解(空间复杂度为O(1),对9取余)
class Solution:
def addDigits(self, num):
if num < 9:
return num
elif num % 9 == 0:
return 9
else:
return num%9
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a,2)+int(b,2))[2:]
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
l,t= 10001,10001
if matrix[i][j] != 0:
if i > 0:
t = matrix[i - 1][j]
if j > 0:
l = matrix[i][j - 1]
matrix[i][j] = min(l,t) + 1
for i in range(len(matrix) - 1, -1 ,-1):
for j in range(len(matrix[0]) - 1, -1, -1):
r,b = 10001,10001
if matrix[i][j] != 0:
if i < len(matrix) - 1:
b = matrix[i + 1][j]
if j < len(matrix[0]) - 1:
r = matrix[i][j + 1]
matrix[i][j] = min(matrix[i][j], min(r,b) + 1)
return matrix
class Solution(object):
def addToArrayForm(self, A, K):
num1 = ""
for i in range(len(A)):
num1 += str(A[i])
output = int(num1) + K
output = str(output)
ans = []
for i in range(len(output)):
ans.append(output[i])
return ans
class Solution:
def twoSum(self, nums, target):
output = []
for i in range(len(nums)):
if (target - nums[i]) in nums and nums.index(target-nums[i])!=i:
output.append(i)
output.append(nums.index(target-nums[i]))
return output
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
nums1 = ""
nums2 = ""
while(l1 != None):
nums1 += str(l1.val)
l1 = l1.next
while(l2 != None):
nums2 += str(l2.val)
l2 = l2.next
intnums1 = int(nums1)
intnums2 = int(nums2)
intoutput = intnums1+intnums2
stroutput = str(intoutput)
#新建两个空链表
tmp_node=ListNode(None)
node=ListNode(None)
#从后往前遍历和字符串,插入链表
for x in stroutput[::-1]:
if not tmp_node.val:
tmp_node.val=x
node=tmp_node
else:
tmp_node.next=ListNode(x)
tmp_node=tmp_node.next
return node
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_length = 0
cur_length = 0
firstpos = 0
lastpos = 1
#s的元素个数为0
if not s:
return 0
#s的元素个数为1
if len(s) == 1:
return 1
#s的元素个数大于1
while(lastpos
class Solution(object):
def reverse(self, x):
strx = str(x)
n = len(strx)
strxx =''
if x >= 0:
for i in range(n):
strxx = strx[i] + strxx
return int(strxx) if int(strxx)<= 2147483647 else 0
else:
for i in range(1,n):
strxx = strx[i] + strxx
return -int(strxx) if -int(strxx)>= -2147483648 else 0
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
#如果nums1为空
if not nums1:
if len(nums2) %2 == 0:
return (nums2[len(nums2)//2]+ nums2[(len(nums2)//2) -1])/2.0
else:
return float(nums2[len(nums2) // 2])
#如果nums2为空
if not nums2:
if len(nums1) %2 == 0:
return (nums1[len(nums1)//2]+ nums1[(len(nums1)//2) -1])/2.0
else:
return float(nums1[len(nums1) // 2])
#两个有序数组 找中位数
total = len(nums1) + len(nums2)
#时间复杂度增加
merge = []
merge = nums1 + nums2
merge.sort()
if total %2 != 0:
return float(merge[total // 2])
else:
return (merge[total//2]+merge[total//2 -1])/2.0
class Solution:
def longestPalindrome(self, s):
if not s :
return ''
#动态规范法
n = len(s)
#若dp[i][j] 等于1,代表字符j到i是回文,若为0,则不是。*注意i>j
dp = [[0]*n for i in range(n)]
max_len = 0
#两个for循环,实现:对每一个i,使得j取值范围为[0,i]。即[0,i],[1,i] ... [i,i]
for i in range(n):
for j in range(i,-1,-1):
#在上面所讲的i,j取值内,有s[i] == s[j] 。这个是设定的触发条件,两个值相等才能是回文数
#设条件x为: i-j <2 ,代表j可以取值i,i-1 程序刚执行时,确保任意i对应单个字符为回文,
#设条件y为: dp[i-1][j+1]值为1 ,代表可以抛弃 i-j<2 的条件。j可以取到所有值[0,i]
if s[i] == s[j] and (i-j <2 or dp[i-1][j+1]) :
dp[i][j] = 1
# 第一遍循环 max_len = 1
if dp[i][j] == 1 and max_len < i-j+1 :
res = s[j:i+1]
max_len =i-j+1
#对于回文为偶数个,'jkllkj', 程序在i取到右边的l时,比较左边的l相等,触发条件同时x条件成立。后面依次比较
#。。。。。奇数个,'abpba' , 程序在i取到右边的b时,比较左边的b相等,触发条件同时y条件成立。后面依次比较
return res
class Solution:
def convert(self, s, numRows):
if numRows < 2: return s
res = ["" for _ in range(numRows)]
i, flag = 0, -1
for c in s:
res[i] += c
if i == 0 or i == numRows - 1: flag = -flag
i += flag
return "".join(res)
class Solution(object):
def myAtoi(self, str1):
"""
:type str: str
:rtype: int
"""
# 如果字符串为空
if not str1:
return 0
out = ""
for i in range(len(str1)):
if str1[i] != " ":
str1=str1[i:]
break
if (str1[0] == "-"):
out += "-"
str1 = str1[1:]
if not str1 or str1[0].isdigit() == False:
return 0
if (str1[0] == "+"):
str1 = str1[1:]
if not str1 or str1[0].isdigit() == False:
return 0
# 如果第一个字符是数字
if (str1[0].isdigit()):
for s in str1:
if s.isdigit() != True:
break
else:out += s
if int(out)>2**31-1:
return 2**31-1
elif int(out)<-2**31:
return -2**31
return int(out)
else: return 0
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
str2 = str(x)
str1 = str2[::-1]
if str1 == str2:
return True
else:
return False
这里的小知识点是 python的str数据类型是没有reverse()这一函数的但是可以用string[::-1]来获取反向的字符串 list数据类型是有的 可以直接进行lista.reverse()!
class Solution:
def isMatch(self,s,p):
ls = len(s)
lp = len(p)
#初始化状态:
dp = [[False]*(lp+1) for _ in range(ls + 1)]
dp[0][0] = True
for i in range(lp):
if p[i] == "*" and dp[0][i-1]:
dp[0][i+1] = True
for i in range(1,ls+1):
for j in range(1, lp+1):
if p[j-1] == s[i-1] or p[j-1] == ".":
dp[i][j] = dp[i-1][j-1]
#匹配 *
elif p[j-1] == "*":
if p[j-2] != s[i-1]:
dp[i][j] = dp[i][j-2]
if p[j-2] == s[i-1] or p[j-2] == ".":
dp[i][j] = dp[i][j-2] or dp[i][j-1] or dp[i-1][j]
return dp[ls][lp]
接下来几天多做几道动态规划的题!
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if not s or len(s) == 1:
return 0
ls = len(s)
dp = [0]*ls
res = 0
for i in range(1,ls):
if s[i] == ")" and s[i-1] == "(":
dp[i] = dp[i-2]+2
elif s[i] == ")" and s[i-1] ==")":
if i-1-dp[i-1] >=0 and s[i-1-dp[i-1]] == "(":
dp[i] = dp[i-2-dp[i-1]]+dp[i-1]+2
if dp[i]>res:
res = dp[i]
return res
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
ls = len(s)
lp = len(p)
dp = [[False]*(lp+1) for _ in range(ls+1)]
dp[0][0] = True
for j in range(1,lp+1):
if p[j-1] == "*":
dp[0][j] = dp[0][j-1]
for i in range(1,ls+1):
for j in range(1, lp+1):
if p[j-1] == s[i-1] or p[j-1] == "?":
dp[i][j] = dp[i-1][j-1]
elif p[j-1] == "*":
dp[i][j] = dp[i][j-1] or dp[i-1][j]
return dp[-1][-1]
class Solution:
def maxSubArray(self, nums):
dp = [0]*len(nums)
output = -float('inf')
if len(nums) == 1:
return nums[0]
for i in range(len(nums)):
dp[i] = max(nums[i],nums[i] + dp[i-1])
if dp[i]>output:
output = dp[i]
return output
class Solution:
def minPathSum(self, grid):
dp = [[0 for i in range(len(grid[0]))] for i in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
if i==0 and j == 0: dp[i][j] = grid[i][j]
elif i == 0:dp[i][j] = dp[i][j-1] + grid[i][j]
elif j == 0:dp[i][j] = dp[i-1][j] + grid[i][j]
else: dp[i][j] = min(dp[i][j-1],dp[i-1][j])+grid[i][j]
return dp[-1][-1]
慢慢地就会做动态规划的题啦!!!
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
elif n == 2:
return 2
dp = [0]*(n+1)
dp[1] = 1
dp[2] = 2
for i in range(3,n+1):
dp[i] = dp[i-1]+dp[i-2]
return dp[n]
class Solution:
def uniquePaths(self, m, n):
if m<=0 or n<=0:
return 0
dp = [[0 for i in range(m)] for i in range(n)]
for i in range(n):#i行
for j in range(m):#j列
if i == 0 and j == 0:
dp[i][j] = 1
elif i == 0:
dp[i][j] = dp[i][j-1]
elif j == 0:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
今天为止,我终于对动态规划问题有一点感觉啦!!!
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
dp = [[0 for i in range(len(obstacleGrid[0]))] for i in range(len(obstacleGrid))]
for i in range(len(obstacleGrid)):#行
for j in range(len(obstacleGrid[0])):#列
if obstacleGrid[i][j] == 1:
dp[i][j] = 0
else:
if i == 0 and j == 0:
dp[i][j] = 1
elif i == 0:
dp[i][j] = dp[i][j-1]
elif j == 0:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
class Solution:
def minDistance(self, word1, word2):
l1 = len(word1)
l2 = len(word2)
dp = [[0]*(l2+1) for i in range(l1+1)]
for j in range(1,l2+1):
dp[0][j] = dp[0][j-1] + 1
for i in range(1,l1+1):
dp[i][0] = dp[i-1][0] + 1
for i in range(1,l1+1):
for j in range(1,l2+1):
if word1[i] == word2[j]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min(dp[i][j-1],dp[i-1][j],dp[i-1][j-1])+1
return dp[-1][-1]
这道题以前做PAT的时候遇到过 今天学习到了!
class Solution:
def minimumTotal(self, triangle):
mini,M = triangle[-1],len(triangle)
for i in range(M-2,-1,-1):
for j in range(len(triangle[i])):
mini[j] = triangle[i][j] +min(mini[j],mini[j+1])
return mini[0]
class Solution:
def longestCommonPrefix(self, strs):
com = ""
flag = 1
minlen = float("Inf")
if len(strs) == 0:
return com
for i in range(len(strs)):#字符串的个数
if len(strs[i]) < minlen:
minlen = len(strs[i])#得到最短字符的长度
minstr = strs[i]
for j in range(minlen):
for i in range(len(strs)):
if strs[i][j] != minstr[j]:
flag = 0
if flag == 1:
com += minstr[j]
return com
class Solution:
def numTrees(self, n):
G = [0]*(n+1)
G[0] = 1
G[1] = 1
for i in range(2,n+1):
for j in range(1,i+1):
G[i] += G[j-1]*G[i-j]
return G[n]
def numTree(self,n):
C = 1
for i in range(0,n):
C = 2*C*(2*i+1)/(i+2)
return int(C)
解答:
class Solution:
def threeSumClosest(self, nums, target):
nums.sort()
diff = 2147483647
res = target
for i in range(len(nums)-2):
left = i+1
right = len(nums)-1
while leftleft and nums[right] == nums[right+1]:
right -= 1
return res
class Solution:
def romanToInt(self, s):
dic = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
output = 0
for i,cha in enumerate(s[:-1]):
if dic[cha]>=dic[s[i+1]]:
output += dic[cha]
else:
output -= dic[cha]
output += dic[s[-1]]
return output
class Solution:
def removeDuplicates(self, nums):
if len(nums) == 0:
return 0
elif len(nums) == 1:
return 1
count = 0
for i in range(1,len(nums)):
if nums[i] != nums[count]:
count += 1
nums[count] = nums[i]
return count + 1
class Solution:
def threeSum(self, nums):
nums.sort()
res = []
for k in range(len(nums)-2):
if nums[k]>0:
break
if k > 0 and nums[k] == nums[k-1]:continue
i = k+1
j = len(nums)-1
while(i 0:
j -= 1
while i
class Solution:
def strStr(self, haystack, needle):
if needle == "":
return 0
else:
for i in range(len(haystack)):
if haystack[i] == needle[0]:
if haystack[i:i+len(needle)] == needle:
return i
return -1
class Solution:
def removeElement(self,nums, val):
# i为不同元素的数组的长度
i = 0
for j in range(0, len(nums)):
# 如果nums[j]不等于val, 则将nums[j]赋值给nums[i]即可, i自增
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i
class Solution:
def fourSum(self, nums, target):
nums.sort()
result = set()
for i in range(len(nums)-3):
for j in range(i+1,len(nums)-2):
left = j+1
right = len(nums)-1
while(left target:
right -= 1
else:
left += 1
output = []
for i in result:
output.append(i)
return output
class Solution:
def searchInsert(self, nums, target):
if target in nums:
return nums.index(target)
else:
for i in range(len(nums)):
if target
class Solution:
def bitwiseComplement(self, N):
# N为十进制
# 1.求其二进制表示
biner = bin(N)
# 2.求其反码
biner = biner[2:]
biner = list(biner)
for i in range(len(biner)):
if biner[i] == '0':
biner[i] = '1'
elif biner[i] == '1':
biner[i] = "0"
biner = "".join(biner)
# 3.将反码表示为十进制数
out = int(biner,2)
return out
class Solution:
def divide(self, dividend, divisor):
sign = (dividend>0) ^ (divisor>0)
dividend = abs(dividend)
divisor = abs(divisor)
count = 0
while(dividend >= divisor):
count += 1
divisor<<=1
result = 0
while count>0:
count -=1
divisor >>= 1
if divisor <= dividend:
result += 1<< count
dividend -= divisor
if sign:result = -result
return result if -(1<<31) <= result <= (1<<31)-1 else (1<<31)-1
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
output = []
if not root:
return
else:
output.append(root.val)
preorderTraversal(root.left)
preorderTraversal(root.right)
return output[]
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
output = []
if not root:
return
else:
output.append(root.val)
preorderTraversal(root.left)
preorderTraversal(root.right)
return output[]
解答:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder, inorder):
if not preorder:
return None
root = TreeNode(preorder[0])
loc = inorder.index(preorder[0])#找到树的根
root.right = self.buildTree(preorder[loc+1:],inorder[loc+1:])
root.left = self.buildTree(preorder[1:loc+1],inorder[:loc])
return root
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, inorder, postorder):
if not inorder:
return None
root = TreeNode(postorder[-1])
loc = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:loc],postorder[:loc])
root.right = self.buildTree(inorder[loc+1:],postorder[loc:len(inorder)-1])
return root
105和106是一样的
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def generateTrees(self, n):
def generate_trees(start, end):
if start>end:
return [None,]
all_trees = []
for i in range(start, end+1):
left_trees = generate_trees(start,i-1)
right_trees = generate_trees(i+1,end)
for l in left_trees:
for r in right_trees:
current_root = TreeNode(i)
current_root.right = r
current_root.left = l
all_trees.append(current_root)
return all_trees
return generate_trees(1,n) if n else[]
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
def inorder(node):
output = []
if not node:
return
inorder(node.left)
output.append(node.val)
inorder(node.right)
return output
if res == sorted(res) and len(res) == len(set(res)):
return True
class Solution:
def letterCombinations(self, digits):
#电话号码所有的组合 字典数据结构
#回溯方法实现
phone = {'2': list("abc"),
'3': list("def"),
'4': list("ghi"),
'5': list("jkl"),
'6': list("mno"),
'7': list("pqrs"),
'8': list("tuv"),
'9': list("wxyz")}
if not digits:
return []
ls = [""]
for i in digits:
ls = [x+y for x in ls for y in phone[i]]
return ls
#回溯算法
class Solution:
def subsets(self, nums):
if not nums:
return []
res = []
n = len(nums)
def helper(index,temp_list):
res.append(temp_list)
for i in range(index,n):
helper(i+1,temp_list+[nums[i]])
helper(0,[])
return res
#回溯算法 没有重复集合
class Solution:
def subsets(self, nums):
if not nums:
return []
res = []
nums.sort()
n = len(nums)
def helper(index,temp_list):
res.append(temp_list)
for i in range(index,n):
if i>index and nums[i] == nums[i-1]:
continue
helper(i+1,temp_list+[nums[i]])
helper(0,[])
return res
class Solution:
def duplicateZeros(self, arr):
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
j = len(arr)
while(i
from itertools import permutations
class Solution:
def permute(self, nums):
return list(permutations(nums))
这里需要介绍一个优秀的库——itertools 里面可以有得到全排列、笛卡尔积等等很多封装的函数
class Solution:
def numTilePossibilities(self, tiles):
counter = [0]*26 #得到[0,0,0,0,0,...........0]
for i in range(len(tiles)):
counter[ord(tiles[i]) - ord("A")] += 1
return self.__dfs(counter)
def __dfs(self,num):
res = 0
for i in range(26):
if num[i] == 0:
continue
res += 1
num[i] -= 1
res += self.__dfs(num)
num[i] += 1
return res
class Solution:
def combine(selfself,n,k):
def back(first = 1,curr = []):
#出口
if len(curr) == k:
output.append(curr[:])
for i in range(first,n+1):
curr.append(i)
back(i+1,curr)
curr.pop()
output = []
back()
return output
class Solution:
def combinationSum3(self,k,n):
def helper(k,start,n,temp):
if k == 0:
if n == 0:
res.append(temp)
return
for i in range(start,10):
if n - i < 0:
break
helper(k-1,i+1,n-i,temp+[i])
res = []
helper(k,1,n,[])
return res
class Solution:
def combinationSum(self, candidates, target):
if not candidates:
return []
length = len(candidates)
res = []
candidates.sort()
def helper(i,tmp,target):
#写出口
if target == 0:
res.append(tmp)
return
if i == length or candidates[i]>target:
return
helper(i,tmp+[candidates[i]],target-candidates[i])
helper(i+1,tmp,target)#回溯
helper(0,[],target)
return res
import itertools
class Solution:
def permuteUnique(self, nums):
#给定一个可包含重复数字的序列,返回所有不重复的全排列
res = []
for i in itertools.permutations(nums):
if i not in res:
res.append(i)
return res
class Solution:
def grayCode(selfself,n):
res = []
if n == 0:
return [0]
def back(now,x):
if len(now) == n:
res.append(int(now,2))
elif x == 0:
back(now+"0",0)
back(now+"1",1)
else:
back(now+"1",0)
back(now + "0", 1)
back("",0)
return res
class Solution:
def letterCasePermutation(self, S):
#字母大小写全排列
res = []
if len(S) == 0:
return []
def back(now,S):#now是现在的str x是即将进入的那个str
if S == "":
res.append(now)
elif S[0].isalpha():
back(now+S[0].upper(),S[1:])
back(now+S[0].lower(),S[1:])
else:
back(now+S[0],S[1:])
back("",S)
return res
class Solution:
def combinationSum2(self, candidates, target):
if candidates == []:
return []
n = len(candidates)
candidates.sort()
res = []
def back(i,temp_sum,temp_list):
if temp_sum == target:
res.append(temp_list)
return
for j in range(i,n):
if temp_sum + candidates[j] >target:
break
if j>i and candidates[j] == candidates[j-1]:
continue#不能重复
back(j+1,temp_sum+candidates[j],temp_list+[candidates[j]])
back(0,0,[])
return res
额..前几天我在干嘛了...额...难道是“欢度双十一”?
class Solution(object):
def countArrangement(self, N):
if N == 15:
return 24679
self.count = 0
def helper(N, pos, used):
if pos > N:
self.count += 1
return
for i in range(1, N + 1):
if used[i] == 0 and (i % pos == 0 or pos % i == 0):
used[i] = 1
helper(N, pos + 1, used)
used[i] = 0
used = [0] * (N + 1)
helper(N, 1, used)
return self.count
class Solution:
def heightChecker(self, heights):
res = sorted(heights)
output = 0
for i in range(len(heights)):
if res[i]!=heights[i]:
output += 1
return output
真是没想到这个题有点难度
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.nums = heapq.nlargest(k,nums)[::-1]#获取堆中最大或者最小的k范围值
def add(self, val: int) -> int:
if len(nums) == k:
if val >self.nums[0]:
heapq.heapreplace(self.nums,val)
return self.nums[0]
heapq.heappush(self.nums, val)
return self.nums[0]
使用快排(.sort())会导致超时 所以使用封装好的堆排序
class Solution:
def wordPattern(self, pattern: str, str: str):
words = str.split(" ")
hash_table_pattern = {}
hash_table_words = {}
if len(words) != len(pattern):
return False
for i,letter in enumerate(pattern):
if hash_table_pattern[letter] != words[i]:
return False
else:
hash_table_pattern[letter] = words[i]
for i,word in enumerate(words):
if hash_table_words.get(word):
if hash_table_words[word] != pattern[i]:
return False
else:
hash_table_words[word] = pattern[i]
return True
class Solution:
def findComplement(self, num):
bintype = bin(num)
#print(bintype)
binstr = str(bintype)[2:]
res = ""
for i in binstr:
if i == "0":
res += "1"
else:res += "0"
return int(res,2)
class Solution:
def sortArrayByParity(self, A):
single = []
oddz = []
for i in A:
if i % 2 == 0:
oddz.append(i)
else:single.append(i)
oddz = oddz+single
return oddz
(心情不好,不开心的时候就去做Leetcode的简单题呀!)
class Solution:
def findWords(self, words):
row1 = "qwertyuiopQWERTYUIOP"
row2 = "asdfghjklASDFGHJKL"
row3 = "zxcvbnmZXCVBNM"
res = []
row1 = set(row1)
row2 = set(row2)
row3 = set(row3)
for i in range(len(words)):
temp = set(words[i])
if temp & row1 == temp or temp & row2 == temp or temp & row3 == temp:
res.append(words[i])
return res
要想好用什么样的数据结构 这个题用集合 很简单!!
class Solution:
def reverseString(self, s):
i = 0
j = len(s)-1
while(i
如果可以用库函数,一行reverse函数就能解决
第一版的答案 思路清晰简单 但是超出时间限制
class Solution:
def smallestRepunitDivByK(self, K):
if K%2 == 0 or K%5 == 0:
return -1
num1 = 1
while(int(num1)%K != 0):
num1 += "1"
return len(num1)
class Solution:
def smallestRepunitDivByK(self, K):
if K%2 == 0 or K%5 == 0:
return -1
num1 = 1
while(num1%K != 0):
num1 = num1*10+1
return len(str(num1))
class Solution:
def invalidTransactions(self, transactions):
trans = [x.split(',') for x in transactions]
res = []
for i in range(len(trans)):
name, time, money, city = trans[i]
time = int(time)
if int(money) > 1000:
res.append(transactions[i])
continue
for j in range(len(trans)):
if i == j:
continue;
name1, time1, money1, city1 = trans[j]
if name1 == name and city1 != city and abs(int(time1) - time) <= 60:
res.append(transactions[i])
break
return res
周末回了杭州 周六是这么久以来睡的最好的一次了
class Solution:
def arrayPairSum(self, nums):
nums.sort()
res = 0
for i in range(len(nums)):
if i%2 == 0:
res += nums[i]
return res
374.题目描述:
二分法找数字:
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
while left<=right:
mid = left + (right-left)//2
if guess(mid) == -1:
right = mid - 1
elif guess(mid) == 1:
left = mid + 1
else:
return mid
#第一遍复杂代码
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
output = []
res = s.split(" ")
for i in res:
tmp = self.reverse(i)
output.append(tmp)
last = output[0]
for i in range(1,len(output)):
last += " "
last += output[i]
return last
def reverse(self, str):
res = ""
num = len(str)
while(num):
num -= 1
res += str[num]
return res
#第二遍简洁代码
class Solution(object):
def reverseWords(self, s):
return " ".join([i[::-1] for i in s.split()])
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
num = len(s) // (2*k) #计算有多少2k
re = len(s) % (2*k) #计算余数
for i in range(num):
temp = s[i*2*k:i*2*k+k][::-1]
s = s[:i*2*k] + temp + s[i*2*k+k:]#str是一种不可变类型
if re < k and re>0:
temp1 = s[-re:][::-1]
s = s[:-re] + temp1
elif re>=k:
tmp = s[-re:][:k][::-1]
s = s[:-re] + tmp + s[k+num*2*k:]
return s
852.题目描述
class Solution:
def peakIndexInMountainArray(self, A):
return A.index(max(A))
这道题我理解错了,按照答案来看,题目是假设一定存在这样的一个i,使这个数组成为山峰式的 而我考虑的是,满足条件的i 一定满足是A[:i+1]==A[:i+1].sort()并且A[i:] == A[i:].sort()(这个地方需要注意 .sort()是没有返回值的None) 但是超时了。
解答:
class Solution:
def divisorGame(self, N):
return N%2 == True
20191202(上周在忙方老师开会的事情)
942.题目描述
解答:
class Solution:
def diStringMatch(self, S: str) -> List[int]:
i=0
j=len(S)
res=[]
for s in S:
if s == "I": #取最小
res.append(i)
i+=1
if s == "D": #取最大
res.append(j)
j-=1
res.append(i)
return res
933.题目描述
解答:
from collections import deque # 通过collections模块导入双端队列deque
class RecentCounter:
def __init__(self):
self.__pingdeque = deque([]) # 定义一个空双端队列
def ping(self, t: int) -> int:
self.__pingdeque.append(t) # 保存ping的时间点t到队列
while t-self.__pingdeque[0] > 3000: # 删除t之前3000ms的时间点
self.__pingdeque.popleft()
return len(self.__pingdeque) # 返回队列中剩下的时间节点个数即是t到t之前3000ms的ping的次数