第一章 数组part02
如果基础不好的录友,建议直接视频讲解,这样避免很多时间浪费,因为没接触过的算法,不是轻易就能靠自己思考想出来的。
拓展题目可以先不做
详细布置
209.长度最小的子数组
题目建议: 本题关键在于理解滑动窗口,这个滑动窗口看文字讲解 还挺难理解的,建议大家先看视频讲解。 拓展题目可以先不做。
题目链接:209. 长度最小的子数组 - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:拿下滑动窗口! | LeetCode 209 长度最小的子数组_哔哩哔哩_bilibili
package org.example.day2;
public class l209 {
public static int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int i = 0;
int length = 2147483647;
for (int j = 0; j < nums.length; j++) {
sum += nums[j];
while (sum >= target) {
int dd = sum - nums[i];
if (dd < target) {
length = Math.min(length, j - i + 1);
break;
} else if (dd == target) {
i++;
sum = dd;
length = Math.min(length, j - i + 1);
break;
} else {
i++;
sum = dd;
}
}
}
if (length == 2147483647) {
length = 0;
}
return length;
}
public static void main(String[] args) {
int[] arr = {2, 3, 1, 2, 4, 3};
System.out.println(minSubArrayLen(7, arr));
}
}
59.螺旋矩阵II
题目建议: 本题关键还是在转圈的逻辑,在二分搜索中提到的区间定义,在这里又用上了。
题目链接:59. 螺旋矩阵 II - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:一入循环深似海 | LeetCode:59.螺旋矩阵II_哔哩哔哩_bilibili
package org.example.day2;
public class l59 {
public static int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
int count = 1, startx = 0, starty = 0;
for (int k = 0; k < n / 2; k++) {
for (int j = startx; j < n - 1 - startx; j++) {
arr[startx][j] = count++;
}
for (int i = starty; i < n - 1 - starty; i++) {
arr[i][n - 1 - starty] = count++;
}
for (int j = n - 1 - startx; j > startx; j--) {
arr[n - 1 - startx][j] = count++;
}
for (int i = n - 1 - starty; i > starty; i--) {
arr[i][starty] = count++;
}
startx++;
starty++;
}
if (n % 2 == 1) {
arr[n / 2][n / 2] = count++;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(" " + arr[i][j]);
}
System.out.println();
}
return arr;
}
public static void main(String[] args) {
int[][] arr = generateMatrix(6);
}
}
区间和
前缀和是一种思维巧妙很实用 而且 很有容易理解的一种算法思想,大家可以体会一下
文章讲解:58. 区间和 | 代码随想录
package org.example.day2;
import java.util.Scanner;
public class k58 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n+1];
int[] p = new int[n+1];
for (int i = 1; i <= n; i++) {
arr[i] = scanner.nextInt();
}
arr[0] = 0;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += arr[i];
p[i] = sum;
}
for (Object pi :p) {
System.out.println(pi);
}
while (scanner.hasNextInt()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(p[b+1] - p[a]);
}
}
}
开发商购买土地
不想写
总结
题目建议:希望大家 也做一个自己 对数组专题的总结
文章链接:代码随想录

2139

被折叠的 条评论
为什么被折叠?



