题目的链接在这里:https://leetcode-cn.com/problems/subarray-product-less-than-k/
题目大意
给定一个正整数数组 nums和整数 k 。请找出该数组内乘积小于 k 的连续的子数组的个数。
一、示意图
二、解题思路
双指针
双指针
代码如下:
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
//该数组中乘积小于k的连续子数组的个数
if(k<=1){
return 0;
}
int prod=1;
int left=0,right=0;
int count=0;
while (right<nums.length){
//右边可以继续往后走
prod*=nums[right];
while (left<=right&&prod>=k){
//说明这个prod太大了 需要修改
prod/=nums[left];
left++;
}
//退出循环 就是符合条件了
count+=right-left+1;
//然后向后移动
right++;
}
return count;
}
}