Leetcode--713. 乘积小于k的子数组
給定一個正整數數組?nums。
找出該數組內乘積小于?k?的連續的子數組的個數。
示例 1:
輸入: nums = [10,5,2,6], k = 100
輸出: 8
解釋: 8個乘積小于100的子數組分別為: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。
需要注意的是 [10,5,2] 并不是乘積小于100的子數組。
說明:
0 < nums.length <= 50000
0 < nums[i] < 1000
0 <= k < 10^6
思路:雙指針法
left與right,right一直向后遍歷,如果乘積大于k,則左指針向右移動,同時乘積ans/nums[left],
而如果左指針移動之后,此刻乘積小于100了,以nums[left]為起始位置滿足條件的為right-left
例如:[2,3,4,5,10,20]? k=100
2*3*4*5大于100了,現在向右移,3*4*5,小于100,所以[3],[3,4],[3,4,5]都是滿足條件的結果
提交的代碼:
class Solution {
? ? public int numSubarrayProductLessThanK(int[] nums, int k) {
? ? ? ? if (k <= 1) return 0;
?? ? ? ? ? ?int t = 1, ans = 0, left = 0;
?? ? ? ? ? ?for (int right = 0; right < nums.length; right++) {
?? ? ? ? ? ? ? ?t *= nums[right];
?? ? ? ? ? ? ? ?while (t >= k) t /= nums[left++];
?? ? ? ? ? ? ? ?ans += right - left + 1;
?? ? ? ? ? ?}
?? ? ? ? ? ?return ans;
? ? }
}
完整的代碼:
public class Solution713 {
?? ? public static int numSubarrayProductLessThanK(int[] nums, int k) {
?? ??? ? if (k <= 1) return 0;
?? ? ? ? ? ?int t = 1, ans = 0, left = 0;
?? ? ? ? ? ?for (int right = 0; right < nums.length; right++) {
?? ? ? ? ? ? ? ?t *= nums[right];
?? ? ? ? ? ? ? ?while (t >= k) t /= nums[left++];
?? ? ? ? ? ? ? ?ans += right - left + 1;
?? ? ? ? ? ?}
?? ? ? ? ? ?return ans;
?? ? ? ?}
?? ? public static void main(String[] args)
?? ? {
?? ??? ? int[] nums = {10,5,2,6};
?? ??? ? int k = 100;
?? ??? ? System.out.println(numSubarrayProductLessThanK(nums,k));
?? ? }
}
?
總結
以上是生活随笔為你收集整理的Leetcode--713. 乘积小于k的子数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对于JDBC的简单理解
- 下一篇: Leetcode--33. 搜索旋转排序