乘积小于 K 的子数组(滑动窗口)


简要分析,这个题目刚开始确实没想到滑动窗口,只是想到动态规划解法,时间复杂度为O(n^{2}),代码如下:

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
         int n = nums.length;
         int ans = 0;
         for(int i = 0 ; i < n ; i++)
         {  
             int temp = nums[i];
             if(temp >= k)
              continue;
            else
               ans++;
             for(int j = 1 ; j < n -i ; j++)
             {   
                temp = temp * nums[i + j];
                 if(temp < k)
                   {
                       ans++;
                   }
                 else
                   break;
             }
         }
         return ans;
    }
}

简单提交后,效果有点惨:

 几乎是马上就要超时的状态。

滑动窗口的解法,因为数组内全部都是大于0的正数,所以随着窗口的扩大,乘积肯定是越来越大的状态,不满足条件时候便缩小窗口,这么一思考,代码的基本逻辑就。

缩小窗口的代码:用ans窗口区间的乘积

 while(i <= j && ans >= k)
             {
                 ans /= nums[i];
                 i++;
             }

 总体代码如下:

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
         int n = nums.length , i = 0;
         int ans = 1;
         int count = 0;

         for(int j = 0 ; j < n ; j++)
         {
             ans *= nums[j];
             while(i <= j && ans >= k)
             {
                 ans /= nums[i];
                 i++;
             }
             count += (j - i + 1);
         }
         return count;
         
    }
}

时间复杂度只有O(n),

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鱼qss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值