在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Your are given an array of positive integers Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than 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:
给定一个正整数数组 找出该数组内乘积小于 示例 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的子数组。 说明:
872ms 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 } Runtime: 880 ms
Memory Usage: 19 MB
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 }
|
请发表评论