有序数组的平方
题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/
文章讲解:https://programmercarl.com/0977.%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E5%B9%B3%E6%96%B9.html
视频讲解: https://www.bilibili.com/video/BV1QB4y1D7ep
关键点:双指针
左闭右闭写法:
image
长度最小的子数组
题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum/
视频讲解:https://www.bilibili.com/video/BV1tZ4y1q7XE
关键点:滑动窗口
滑动窗口模板:
/* 滑动窗口算法框架 */
void slidingWindow(string s, string t) {
unordered_map<char, int> need, window;
for (char c : t) need[c]++;
int left = 0, right = 0;
int valid = 0;
while (right < s.size()) {
// c 是将移入窗口的字符
char c = s[right];
// 增大窗口
right++;
// 进行窗口内数据的一系列更新
...
/*** debug 输出的位置 ***/
printf("window: [%d, %d)\n", left, right);
/********************/
// 判断左侧窗口是否要收缩
while (window needs shrink) {
// d 是将移出窗口的字符
char d = s[left];
// 缩小窗口
left++;
// 进行窗口内数据的一系列更新
...
}
}
}
螺旋矩阵II
题目链接:https://leetcode.cn/problems/spiral-matrix-ii/
文章讲解:https://programmercarl.com/0059.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html
视频讲解:https://www.bilibili.com/video/BV1SL4y1N7mV/
关键点:模拟
外层以一个for循环记录转过了几圈(offset变量记录,循环到n//2)
内层四个for循环模拟转四条边
用starti,startj记录每一圈左上角开始的坐标,每转完一圈加一
注意坚持左闭右开写法
def generateMatrix(self, n: int) -> List[List[int]]:
x=[[0]*n for i in range(n)]
starti,startj=0,0
loop=n//2
count=1
for k in range(loop):
for j in range(startj,n-k-1):
x[starti][j]=count
count+=1
for i in range(starti,n-k-1):
x[i][n-k-1]=count
count+=1
for a in range(k-n+1,-startj):
x[n-k-1][-a]=count
count+=1
for b in range(k-n+1,-starti):
x[-b][startj]=count
count+=1
starti+=1
startj+=1
if n%2!=0:
x[n//2][n//2]=count
return x