目录

​一、插入区间​

​1、题目描述​

​2、题解​

​3、源码​

​二、最后一个单词的长度​

​1、题目描述​

​2、题解​

​3、源码​

​三、螺旋矩阵Ⅱ​

​1、题目描述​

​2、题解​

​3、源码​

​四、旋转链表​

​1、题目描述​

​2、题解​

​3、源码​

​五、不同路径​

​1、题目描述​

​2、题解​

​3、源码​


一、插入区间

1、题目描述

LeetCode刷题(57、58、59、61、62)_螺旋矩阵

 

2、题解

LeetCode刷题(57、58、59、61、62)_python_02

3、源码

class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
intervals.append(newInterval)
intervals=sorted(intervals)
res=[]
n=len(intervals)
i=0
while(i<n):
left=intervals[i][0]
right=intervals[i][1]
while(i<n-1 and intervals[i+1][0]<=right):
i=i+1
right=max(intervals[i][1],right)
res.append([left,right])
i=i+1
return res

二、最后一个单词的长度

1、题目描述

LeetCode刷题(57、58、59、61、62)_python_03

 

2、题解

LeetCode刷题(57、58、59、61、62)_python_04

 

3、源码

class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split( )[-1])

三、螺旋矩阵Ⅱ

1、题目描述

LeetCode刷题(57、58、59、61、62)_链表_05

2、题解

LeetCode刷题(57、58、59、61、62)_链表_06

3、源码

class Solution:
def generateMatrix(self, n: int) -> [[int]]:
l, r, t, b = 0, n - 1, 0, n - 1
mat = [[0 for _ in range(n)] for _ in range(n)]
num, tar = 1, n * n
while num <= tar:
for i in range(l, r + 1): # left to right
mat[t][i] = num
num += 1
t += 1
for i in range(t, b + 1): # top to bottom
mat[i][r] = num
num += 1
r -= 1
for i in range(r, l - 1, -1): # right to left
mat[b][i] = num
num += 1
b -= 1
for i in range(b, t - 1, -1): # bottom to top
mat[i][l] = num
num += 1
l += 1
return mat

四、旋转链表

1、题目描述

LeetCode刷题(57、58、59、61、62)_python_07

LeetCode刷题(57、58、59、61、62)_链表_08

 

 

2、题解

LeetCode刷题(57、58、59、61、62)_结点_09

3、源码

class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k == 0 or not head or not head.next: #k为0 或者链表长度为0或1
return head

n = 1
cur = head
while cur.next: #寻找尾结点,并记录链表长度n
cur = cur.next
n += 1

add = n - k % n
if add == n: #当k是n的整数倍,直接返回原链表,不做改动
return head

cur.next = head #否则进行首尾相连,形成环
while add:
# 找到新链表的最后一个结点(即原链表的第 (n−1)−(k mod n) 个节点)
cur = cur.next
add -= 1

ret = cur.next #根据找到的新链表最后一个结点的位置,把环断开
cur.next = None
return ret


五、不同路径

1、题目描述

2、题解

LeetCode刷题(57、58、59、61、62)_链表_10

LeetCode刷题(57、58、59、61、62)_螺旋矩阵_11

 

LeetCode刷题(57、58、59、61、62)_链表_12

 

3、源码

class Solution(object):
def uniquePaths(self, m, n):
d = {}
def dfs(i, j):
# 如果(i,j)在缓存中则直接返回
if (i, j) in d:
return d[i,j]
# 到达边界时,返回 1
if i == m - 1 or j == n - 1:
return 1
# 继续递归调用,往下i+1,往右j+1
d[i,j] = dfs(i + 1, j) + dfs(i, j + 1)
return d[i,j]
return dfs(0,0)