/
Offer009.java
40 lines (38 loc) · 1013 Bytes
/
Offer009.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.yore.offer2;
/**
* @author Yore
* @date 2022/1/18 15:12
* @description
*/
public class Offer009 {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int multi = 1;
int r = i;
while (r < nums.length) {
multi *= nums[r];
if (multi < k) {
count++;
r++;
} else {
break;
}
}
}
return count;
}
public int numSubarrayProductLessThanK2(int[] nums, int k) {
int left = 0;
int count = 0;
int multi = 1;
for (int right = 0; right < nums.length; right++) {
multi *= nums[right];
while (left <= right && multi >= k) {
multi /= nums[left++];
}
count += right >= left ? (right - left + 1) : 0;
}
return count;
}
}