★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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 }