zoukankan      html  css  js  c++  java
  • leetcode713 Subarray Product Less Than K

     1 """
     2 Your are given an array of positive integers nums.
     3 Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
     4 Example 1:
     5 Input: nums = [10, 5, 2, 6], k = 100
     6 Output: 8
     7 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
     8 Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
     9 """
    10 """
    11 正确做法,双指针加滑动窗口
    12 很是巧妙
    13 pro为乘积,pro不断乘以nums[j]得到子数组乘积,满足条件小于k时
    14 !!!
    15 res +=(j-i+1),res是计数器。
    16 滑动窗口内元素间的相互组合的数量
    17 """
    18 class Solution1:
    19     def numSubarrayProductLessThanK(self, nums, k):
    20         res, i = 0, 0
    21         pro = 1 #乘积
    22         if k <= 1:  # 对于案例nums=[1, 2, 3] k=0  和 nums=[1, 1, 1] k=1
    23             return 0
    24         for j in range(len(nums)):
    25             pro = pro * nums[j]
    26             while pro >= k:
    27                 pro = pro // nums[i]
    28                 i += 1
    29             res += j - i + 1 #!!!这个很关键
    30         return res
    31 
    32 """
    33 我的解法超时,
    34 对于输入nums = [1, 1, 1, 1......,1] k=5
    35 """
    36 class Solution2:
    37     def numSubarrayProductLessThanK(self, nums, k):
    38         res = 0
    39         for i in range(len(nums)):
    40             pro = 1
    41             j = i
    42             while j < len(nums):
    43                 if nums[j] * pro < k:
    44                     res += 1
    45                     pro = nums[j] * pro
    46                     j += 1
    47                 else:
    48                     break
    49         return res
  • 相关阅读:
    MySQL-事务相关知识
    Linux脚本-自动ping网址列表
    洛谷 P2453 [SDOI2006]最短距离
    洛谷 P2915 [USACO08NOV]Mixed Up Cows G
    洛谷 P2473 [SCOI2008] 奖励关
    洛谷 P3391 【模板】文艺平衡树
    洛谷 P4146 序列终结者
    洛谷 P1486 [NOI2004] 郁闷的出纳员
    洛谷 P2596 [ZJOI2006]书架
    性能测试工具Jmeter02-安装配置
  • 原文地址:https://www.cnblogs.com/yawenw/p/12346491.html
Copyright © 2011-2022 走看看