栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


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

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),

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862353.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号