第四天
27.移除元素
https://leetcode.cn/problems/remove-element/
数组 双指针
给你一个数组
num
和一个值val
,你需要原地
移除所有数值等于val
的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用O(1)
额外空间并原地
修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
快慢指针法:定义两个指针,快指针 fast \textit{fast} fast 指向当前将要处理的元素,慢指针 slow \textit{slow} slow 指向下一个将要赋值的位置。
-
如果快指针指向的元素不等于 val \textit{val} val,它一定是输出数组的一个元素,我们就将快指针指向的元素复制到慢指针位置,然后将快慢指针同时右移;
-
如果快指针指向的元素等于 val \textit{val} val,它不能在输出数组里,此时慢指针不动,快指针右移一位。
class Solution():
def removeElement(self, nums: List[int], val: int) -> int:
n = len(nums)
if n == 0: return 0
slow, fast = 0, 0
while slow < n and fast < n: # 其实只要fast < n就行了
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
复杂度分析
时间复杂度:
O
(
n
)
O(n)
O(n),其中 n 为序列的长度。我们只需要遍历该序列至多两次。
空间复杂度:
O
(
1
)
O(1)
O(1)。我们只需要常数的空间保存若干变量。
209.长度最小的数组
https://leetcode.cn/problems/minimum-size-subarray-sum/
数组 滑动窗口
给定一个含有
n
个正整数的数组和一个正整数target
。
找出该数组中满足其和≥ target
的长度最小的连续子数组
[ n u m s l , n u m s l + 1 , . . . , n u m s r − 1 , n u m s r ] [nums_l, nums_{l+1}, ..., nums_{r-1}, nums_r] [numsl,numsl+1,...,numsr−1,numsr],并返回其长度。如果不存在符合条件的子数组,返回 0 。
方法一:暴力法
需要思考,双层循环,求长度最小。
方法二:滑动窗口法(双指针)
滑动窗口法也可以理解为双指针,两个指针为滑动窗口的起始位置和终止位置,
实现滑动窗口,主要确定如下三点:
-
窗口内是什么?
-
如何移动窗口的起始位置?
-
如何移动窗口的结束位置?
-
窗口就是
满足其和 ≥ s
的长度最小的连续
子数组。 -
窗口的起始位置如何移动:如果当前窗口的值大于s了,窗口就要向前移动了(也就是该缩小了)。
-
窗口的结束位置如何移动:窗口的结束位置就是遍历数组的指针,也就是for循环里的索引。
解题的关键在于窗口的起始位置如何移动。
每一轮迭代,将 nums [ e n d ] \text{nums}[end] nums[end] 加到 sum \textit{sum} sum,如果 sum ≥ s \textit{sum} \ge s sum≥s,则更新子数组的最小长度(此时子数组的长度是 end − start + 1 \textit{end}-\textit{start}+1 end−start+1),然后将 nums [ s t a r t ] \text{nums}[start] nums[start] 从 sum \textit{sum} sum 中减去并将 start \textit{start} start 右移,直到 sum < s \textit{sum} < s sum<s,在此过程中同样更新子数组的最小长度。在每一轮迭代的最后,将 end \textit{end} end 右移。
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
# 滑动窗口法(双指针)
res = float("inf")
Sum = 0
index = 0 # 滑动窗口的起始位置
for i in range(len(nums)): # 滑动窗口的终止位置
Sum += nums[i]
while Sum >= target:
res = min(res, i - index + 1)
Sum -= nums[index]
index += 1
return 0 if res == float("inf") else res
拓展:
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和=target
的长度最小的连续子数组。
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
# 滑动窗口法(双指针)
res = float("inf")
Sum = 0
index = 0 # 滑动窗口的起始位置
for i in range(len(nums)): # 滑动窗口的终止位置
Sum += nums[i]
while Sum > target: # 大于target时向前滑动
Sum -= nums[index]
index += 1
while Sum == target: # 等于tartget时,记录子数组长度
res = min(res, i - index + 1)
Sum -= nums[index]
index += 1
return 0 if res == float("inf") else res
566.重塑矩阵
https://leetcode.cn/problems/reshape-the-matrix/
数组 矩阵 模拟
可以直接从二维数组nums 得到 r 行 c 列的重塑矩阵:
- 设 nums 本身为 m 行 n 列,如果 m n ≠ r c mn \neq rc mn=rc,那么二者包含的元素个数不相同,因此无法进行重塑;
- 否则,对于
x
∈
[
0
,
m
n
)
x \in [0, mn)
x∈[0,mn),第 x 个元素在 nums 中对应的下标为
(
x
/
n
,
x
%
n
)
(x ~/~ n, x~\%~ n)
(x / n,x % n),而在新的重塑矩阵中对应的下标为
(
x
/
c
,
x
%
c
)
(x ~/~ c, x~\%~ c)
(x / c,x % c)。我们直接进行赋值即可。
重点:对于 x ∈ [ 0 , m n ) x \in [0, mn) x∈[0,mn),第 x 个元素在 nums 中对应的下标为 ( x / n , x % n ) (x ~/~ n, x~\%~ n) (x / n,x % n),而在新的重塑矩阵中对应的下标为 ( x / c , x % c ) (x ~/~ c, x~\%~ c) (x / c,x % c)。
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
ans = [[0] * c for _ in range(r)]
for x in range(m * n):
ans[x // c][x % c] = mat[x // n][x % n]
return ans
118.杨辉三角
https://leetcode.cn/problems/pascals-triangle/
数组 动态规划
给定一个非负整数
numRows
,生成「杨辉三角」的前numRows
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
每个数字等于上一行的左右两个数字之和,可用此性质写出整个杨辉三角。即第 n行的第 i 个数等于第 n-1 行的第 i-1 个数和第 i 个数之和。这也是组合数的性质之一,即 C n i = C n − 1 i + C n − 1 i − 1 \mathcal{C}_n^i=\mathcal{C}_{n-1}^i+\mathcal{C}_{n-1}^{i-1} Cni=Cn−1i+Cn−1i−1
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = []
for i in range(numRows):
row = []
for j in range(0, i+1): # 第i行
if j == 0 or j == i:
row.append(1) # 第i行的第一个数和最后一个数为1
else: # 第i-1行的第j-1个数和第j个数之和
row.append(res[i-1][j-1] + res[i-1][j])
res.append(row)
return res