博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
乘积小于k的子数组的个数 Subarray Product Less Than K
阅读量:7222 次
发布时间:2019-06-29

本文共 853 字,大约阅读时间需要 2 分钟。

  hot3.png

问题:

Your are given an array of positive integers nums.

Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.

Example 1:

Input: nums = [10, 5, 2, 6], k = 100Output: 8Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Note:

  • 0 < nums.length <= 50000.
  • 0 < nums[i] < 1000.
  • 0 <= k < 10^6.

解决:

①  双指针 + 滑动窗口

class Solution { //21ms

    public int numSubarrayProductLessThanK(int[] nums, int k) {
        if (k <= 1) return 0;
        int res = 0;
        int val = 1;
        int left = 0;
        for (int i = 0;i < nums.length;i ++){
            val *= nums[i];
            while(val >= k) val /= nums[left ++];
            res += i - left + 1;
        }
        return res;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1607625

你可能感兴趣的文章
创建文件夹、新建txt文件
查看>>
js form表单 鼠标移入弹出提示功能
查看>>
LFS7.10——准备Host系统
查看>>
Redis.py客户端的命令总结【三】
查看>>
mac 安装secureCRT
查看>>
/var/adm/wtmp文件太大该怎么办?
查看>>
反应器模式 vs 观察者模式
查看>>
Algernon's Noxious Emissions POJ1121 zoj1052
查看>>
iOS-数据持久化-对象归档
查看>>
iOS开发UI篇—程序启动原理和UIApplication
查看>>
MUI 里js动态添加数字输入框后,增加、减少按钮无效
查看>>
python pip 更换国内安装源(windows)
查看>>
结对编程2后篇
查看>>
oracle exp 和 imp 数据和表结构互相独立导出导入
查看>>
iphone-common-codes-ccteam源代码 CCNSPredicate.m
查看>>
这次项目中应该注意的问题和应该保持的好习惯
查看>>
python-数据结构化与保存
查看>>
LeetCode - 551. Student Attendance Record I
查看>>
Java用户线程和守护线程
查看>>
ClassLoader类加载机制&&JVM内存管理
查看>>