题目链接

乘积小于K的子数组

题目描述

image.png

解题思路

方法一:滑动窗口

  1. class Solution {
  2. public int numSubarrayProductLessThanK(int[] nums, int k) {
  3. int len = nums.length;
  4. int result = 0;
  5. int cnt = 1;
  6. int startIdx = 0;
  7. for(int i=0; i<len; i++) {
  8. cnt *= nums[i];
  9. if(cnt < k) {
  10. result += (i - startIdx + 1);
  11. } else {
  12. for(;startIdx<i; ) {
  13. cnt /= nums[startIdx++];
  14. if(cnt < k) {
  15. break;
  16. }
  17. }
  18. if(cnt < k) {
  19. result += (i - startIdx + 1);
  20. }
  21. }
  22. }
  23. return result;
  24. }
  25. }