代码随想录day2:数组part2

代码随想录

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值