当前位置:网站首页>Force deduction solution summary 713- subarray with product less than k

Force deduction solution summary 713- subarray with product less than k

2022-06-12 02:08:00 Lost summer

Directory links :

Force buckle programming problem - The solution sums up _ Share + Record -CSDN Blog

GitHub Synchronous question brushing items :

https://github.com/September26/java-algorithms

Original link : Power button


describe :

Give you an array of integers nums And an integer k , Please return that the product of all elements in the subarray is strictly less than k The number of consecutive subarrays of .
 

Example 1:

Input :nums = [10,5,2,6], k = 100
Output :8
explain :8 The product is less than 100 The subarrays of are :[10]、[5]、[2],、[6]、[10,5]、[5,2]、[2,6]、[5,2,6].
It should be noted that [10,5,2] It's not that the product is less than 100 Subarray .
Example 2:

Input :nums = [1,2,3], k = 0
Output :0
 

Tips : 

1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/subarray-product-less-than-k
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Their thinking :

*  Their thinking :
*  If this question is double every time for loop , It is very simple , however O(n2) Complexity , Will exceed the time limit .
*  My idea is that each cycle , From 0 Bit start , Multiplicative multiplication . If it is greater than k, If you continue to multiply, it must be greater than K, Reset the current result , And then from the 1 Bit start 

Code :

public class Solution713 {

    public int numSubarrayProductLessThanK(int[] nums, int k) {
        int result = 0;
        int currentValue = 1;
        for (int i = 0; i < nums.length; i++) {
            currentValue = 1;
            for (int j = i; j < nums.length; j++) {
                currentValue *= nums[j];
                if (currentValue >= k) {
                    break;
                }
                result++;
            }
        }
        return result;
    }
}

原网站

版权声明
本文为[Lost summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120202544534.html