LeetCode 第26天

昨天蔚来笔试的三道题分别是:

  1. 二叉树合并:

https://leetcode.cn/problems/merge-two-binary-trees/

  1. 爬楼梯:

https://leetcode.cn/problems/climbing-stairs/ 不同的是题目中可以爬三级,不过思路都一样

  1. 滑动窗口的最大值:

https://leetcode.cn/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/

都比较简单,全部ac了

和大于等于target的最短子数组

给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

分析:

使用滑动窗口。初始化start=end=0;sum=0;当end小于nums.length且sum小于target时:end++;否则len=min(len,end-start+1),然后不断地sum -= nums[start], start++直到sum<target。

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        if (nums.length == 0) return 0;
        int start = 0, end = 0;
        int res = Integer.MAX_VALUE;
        int sum = 0;
        while (end < nums.length) {
            sum += nums[end];
            while (sum >= target) {
                res = Math.min(res, end - start + 1);
                sum -= nums[start];
                start++;
            }
            end++;
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

乘积小于K的子数组

给定一个正整数数组 nums和整数 k ,请找出该数组内乘积小于 k 的连续的子数组的个数。

分析:

与上题思路基本一致。

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
        int res = 0, prod = 1, start = 0;
        for (int i = 0; i < nums.length; i++) {
            prod *= nums[i];
            while (start<=i && prod>=k){
                prod /= nums[start];
                start++;
            }
            res += i-start+1;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值