您的位置:首页 > 其它

Leetcode:713.Subarray Product Less Than K

2017-11-04 11:00 441 查看
题目描述:

题目:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: