Leetcode:713.Subarray Product Less Than K
来源:互联网 发布:mysql官网下载旧版本 编辑:程序博客网 时间:2024/06/07 07:06
题目描述:
题目:
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 = 100
Output: 8
Explanation: 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.
代码以及分析:
/** * 题目描述: 就是给定一个数组,有n个数字,然后下列的子数组是满足条件的,给定一个k * 然后子数组数字的乘积肯定是小于K的,这样就是满足条件的。 * 比如给定numbs = [10, 5, 2, 6], k = 100 * [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] 返回8 * 比如[10,5,2] 因为他们的乘积等于100了。 * 思路分析:或许你会想到暴力搜索来实现这个问题(遍历所有的子数组算乘积和K比较,两个for循环就行了),但是这样是不能通过。 * Step: * 1.遍历原数组,用prod乘上当前遍历到的数字, * 2.然后进行while循环,如果prod大于等于k,那么这种解就是不合适的,则滑动窗口的左边界需要向右移动一位, * 3.删除最左边的数字,那么少了一个数字,乘积就会改变,所以用prod除以最左边的数字,然后左边右移一位,即left自增1。 * 4.当我们确定了窗口的大小后,就可以统计子数组的个数了,就是窗口的大小。 * 5.为啥呢,比如[5 2 6]这个窗口,k还是100,右边界刚滑到6这个位置,这个窗口的大小就是包含6的子数组乘积小于k的个数,即[6], [2 6], [5 2 6],正好是3个。 * 6.所以窗口每次向右增加一个数字,然后左边去掉需要去掉的数字后,窗口的大小就是新的子数组的个数,每次加到结果res中即可。 * @param args */
public static int numSubarrayProductLessThanK(int [] nums,int k){ if (k <= 1) return 0; int res = 0, prod = 1, left = 0; for (int i = 0; i < nums.length; ++i) { prod *= nums[i]; while (prod >= k) prod /= nums[left++]; res += i - left + 1; } return res; }
阅读全文
0 0
- Leetcode:713.Subarray Product Less Than K
- leetcode 713 Subarray Product Less Than K
- leetCode-Subarray Product Less Than K
- 713.Subarray Product Less Than K
- 713. Subarray Product Less Than K
- 713. Subarray Product Less Than K
- LWC 55:713. Subarray Product Less Than K
- Add to List 713. Subarray Product Less Than K
- LeetCode-713:Subarray Product Less Than K (乘积小于K的子数组个数) -- medium
- weekly contest 55 第三题 Subarray Product Less Than K
- Subarray Product Less Than K问题及解法
- find a subarray that contains the largest sum, constraint that sum is less than k
- Maximum Product Subarray 【LeetCode】
- [LeetCode] Maximum Product Subarray
- leetcode-Maximum Product Subarray
- Maximum Product Subarray -- LeetCode
- LeetCode-Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- 配置postfix和dovecot启用SSL以加密连接
- U-BOOT源码目录
- 直线搜索/一维搜索
- 微信小程序自定义组件Dialog
- Spring学习之路-高级装配
- Leetcode:713.Subarray Product Less Than K
- .NET-简单的委托实例
- Android activity的四种启动模式
- Oracle:聚合函数
- MyEclipse10的项目中把 java EE 5 Libraries 删掉后怎么重新导入
- volatile关键字解析
- UML交互图(顺序图和交互图)
- 设计模式【模板模式Template Pattern】
- 恢复Excel批注框到默认位置