第一次复习
7.8 题目
1.字符串中的第一个唯一字符(熟悉)
class Solution:
def firstUniqChar(self, s):
res = {}
for i,j in enumerate(s):
if j not in res:
res[j] = i
elif j in res:
res[j] = -1
for i in s:
if res[i] != -1:
return res[i]
return -1
小结:时间复杂度略大,空间复杂度较大。Counter()函数的使用,同时需要注意的是 enumerate() 函数使用时,i 为编号,j 为对应的内容。
解决方式:
class Solution:
def firstUniqChar(self, s):
d = Counter(s)
'''得到Counter({'e': 3, 'l': 1, 't': 1, 'c': 1, 'o': 1, 'd': 1})'''
for i, j in enumerate(s):
'''得到 i = 0,1,... j = l,e,e,t,c,o,d,e'''
if d[j] == 1:
return i
return -1
2.重新格式化电话号码(模糊)
class Solution(object):
def reformatNumber(self, number):
number = number.replace(" ","").replace("-","")
rem = len(number)%3
num = len(number)//3 - 1 if rem in (0,1) else len(number)//3
ret = []
for i in range(num):
ret.append(number[i*3:(i+1)*3])
if rem == 1:
ret.append(number[num*3:num*3+2])
ret.append(number[num*3+2:num*3+4])
else:
ret.append(number[num*3:])
return '-'.join(ret)
小结:步骤很复杂,需要仔细琢磨琢磨。
7.12 题目
1.青蛙跳阶(模糊)
class Solution(object):
def numWays(self, n):
x,y = 1,1
for i in range(n):
x , y = y , x+y
return x
小结:动态规划问题需要的几大步骤需要掌握,并且需要掌握动态规划所对应的题目场景。
2. 最长递增子序列(忘记)
class Solution(object):
def lengthOfLIS(self, nums):
if len(nums) == 0 :
return 0
dp = []
for i in range(len(nums)):
dp.append(1)
for j in range(i):
if dp[i] > dp[j]:
dp[i] = max(dp[i] , dp[j]+1)
return max(dp)
小结:多刷题,菜就多练练
3. 解决智力问题(忘记)
class Solution:
def mostPoints(self, questions: List[List[int]]) -> int:
n = len(questions)
dp = [0] * (n+1)
for i in range(n - 1, -1, -1):
dp[i] = max(dp[i + 1], questions[i][0] + dp[min(n, i + questions[i][1] + 1)])
return dp[0]
小结:为什么我感觉自己就是个废物呢,写啥啥错
7.13 题目
1.两数之和(模糊)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i,num in enumerate(nums):
if target - num in hashtable:
return [i,hashtable[target - num]]
hashtable[num] = i
return []
小结:暴力破解速度太慢,时间复杂度高达\(O(N^2)\),建议使用哈希表存储进行解题。
2.两数相加(熟悉)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
result = curr = ListNode()
num = 0
passed = 0
while l1 or l2:
a = l1.val if l1 else 0
b = l2.val if l2 else 0
num = a+b+passed
curr.next = ListNode(num%10)
passed = num // 10
if l1: l1 = l1.next
if l2: l2 = l2.next
curr = curr.next
if passed == 1:
curr.next = ListNode(1)
return(result.next)
小结:各个步骤需要注意,每一次循环后的三个结点的更新,当 l1 或者 l2 结点结束时也要注意返回 0 值,若左后有进位也需要考虑进去。
7.15 题目
1.无重复字符的最长子串(忘记)
class Solution(object):
def lengthOfLongestSubstring(self, s):
dic, res, i = {}, 0, -1 # i是左指针
for j in range(len(s)): # j是右指针
if s[j] in dic: # 若当前元素在之前出现过,更新左指针
# 当之前出现的元素在左右指针中间,左指针更新为之前元素下标,若不在中间,左指针不变
i = max(i, dic[s[j]])
dic[s[j]] = j # 将当前元素加入哈希表中
res = max(res, j - i)
return res
总结:寄