1. 程式人生 > >【LeetCode】713. Subarray Product Less Than K 解題報告(Python)

【LeetCode】713. Subarray Product Less Than K 解題報告(Python)

題目描述:

Your are given an array of positive integers nums.

Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.

Example 1:

Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Note:

  • 0 < nums.length <= 50000.
  • 0 < nums[i] < 1000.
  • 0 <= k < 10^6.

題目大意

找出一個數組中連續子陣列的乘積有多少個小於k的。

解題方法

因為只要求個數,不要求列出來,那麼可以想到雙指標。

這個題的做法還是很簡單的,使用兩個指標確定子陣列的邊界,然後求子陣列的乘積,如果乘積大於等於k了,需要移動左指標。每次移動有指標之後,符合題目要求的結果增加的是以右指標為邊界的子陣列數量,也就是r - l + 1。

注意移動左指標的時候,不能超過右指標。

時間複雜度是O(N),空間複雜度是O(1)。

class Solution
(object): def numSubarrayProductLessThanK(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ N = len(nums) prod = 1 l, r = 0, 0 res = 0 while r < N: prod *= nums[r] while l <=
r and prod >= k: prod /= nums[l] l += 1 res += r - l + 1 r += 1 return res

參考資料:

日期

2018 年 10 月 14 日 —— 周賽做出來3個題,開心