★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ujyblxnn-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Your are given an array of positive integers nums
.git
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k
.github
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
.給定一個正整數數組 nums
。less
找出該數組內乘積小於 k
的連續的子數組的個數。spa
示例 1:code
輸入: 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的子數組。
說明:htm
0 < nums.length <= 50000
0 < nums[i] < 1000
0 <= k < 10^6
872msblog
1 class Solution { 2 func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { 3 guard nums.count > 0 else { 4 return 0 5 } 6 7 var movingIndex: Int = 0 8 var startIndex: Int = 0 9 var product: Int = 1 10 var result: Int = 0 11 12 while movingIndex < nums.count { 13 let num = nums[movingIndex] 14 product *= num 15 while product >= k && startIndex < movingIndex { 16 product /= nums[startIndex] 17 startIndex += 1 18 } 19 if product < k { 20 result += movingIndex - startIndex + 1 21 } 22 movingIndex += 1 23 } 24 25 return result 26 } 27 }
1 class Solution { 2 func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { 3 if k <= 1 {return 0} 4 var res:Int = 0 5 var prod:Int = 1 6 var left:Int = 0 7 for i in 0..<nums.count 8 { 9 prod *= nums[i] 10 while(prod >= k) 11 { 12 prod /= nums[left] 13 left += 1 14 } 15 res += i - left + 1 16 } 17 return res 18 } 19 }
896ms
1 class Solution { 2 func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { 3 4 var left: Int = 0 5 var sum = 1,totle = 0,right = 0; 6 7 if k <= sum { 8 return 0 9 } 10 11 for (index, value) in nums.enumerated() { 12 13 sum *= value; 14 while sum >= k { 15 sum = sum/nums[left] 16 left += 1 17 } 18 totle += ((right - left) + 1) 19 right += 1 20 21 } 22 return totle; 23 } 24 }