代码随想录
209.长度最小的子数组 leetcode地址
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int result = Integer.MAX_VALUE;
int i = 0;
int sum = 0;
int subL = 0;
for(int j = 0;j < nums.length;j++){
sum += nums[j];
while(sum >= target){
subL = j - i + 1;
sum -= nums[i];
i++;
result = Math.min(subL,result);
}
}
return result;
}
}
错误,用例三未通过,sum一直未大于target,应该返回0。
输入:target = 11, nums = [1,1,1,1,1,1,1,1] 输出:0
输出应该为
return result == Integer.MAX_VALUE ? 0 : result;
如果是MAX就返回0,不是返回result
59.螺旋矩阵IIleetcode地址
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
int firstx = 0;
int firsty = 0;
int size = 1;
int num = 1;
int circle = 1;
int i,j;
while(circle <= n/2){
for(j = firstx;j < n-size;j++){
nums[firstx][j] = num++;
}
for(i = firsty;i < n-size;i++){
nums[i][j] = num++;
}
for(;j>firstx;j--){
nums[i][j] = num++;
}
for(;i>firsty;i--){
nums[i][firsty] = num++;
}
firstx++;
firsty++;
size++;
circle++;
}
if(n % 2 == 1 ){
nums[n/2][n/2] = num++;
}
return nums;
}
}
58. 区间和卡码网地址
主要使用了前缀和思想
如上图,如果我们要求 区间下标 [2, 5] 的区间和,那么应该是 p[5] - p[1],而不是 p[5] - p[2]。
练习ACM模式,背一下输入输出格式
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] vec = new int[n];
int[] p = new int[n];
int presum = 0;
for (int i = 0; i < n; i++) {
vec[i] = scanner.nextInt();
presum += vec[i];
p[i] = presum;
}
while (scanner.hasNextInt()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum;
if (a == 0) {
sum = p[b];
} else {
sum = p[b] - p[a - 1];
}
System.out.println(sum);
}
scanner.close();
}
}
数组总结
算法:3h
博客:0.5h