我正在练习双指针技巧来解决最大连续1的问题 - LeetCode
该解决方案使用Kadane算法。Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Note:
- The input array will only contain
0
and1
.- The length of input array is a positive integer and will not exceed 10,000
class Solution:
def findMaxConsecutiveOnes(self, nums: "List[int]") -> int:
loc_max = glo_max = 0
for i in range(len(nums)):
if nums[i] == 1:
loc_max += 1
elif nums[i] != 1:
glo_max = max(glo_max, loc_max)
loc_max = 0
#in case of the corner case [.....,1 ,1, 1]
return max(glo_max, loc_max)
这个解决方案的问题在于它不是一个像快慢指针那样得体的解决方案。(它没有明确的慢指针)
使用慢指针的直觉想法是使用慢指针记住连续1的起始索引,当快指针到达非1时,关系为
长度=快指针-慢指针
。然而,很难将慢指针定位到第一个1。例如
[0, 0, 0, 1, 1, 1, 1]
,作为一个妥协性的建议,重新定义慢指针为一个一组中向前的非1元素,当快指针到达另一个非1元素时。使用关系:长度=快指针-慢指针+1
class Solution:
def findMaxConsecutiveOnes(self, nums: "List[int]") -> int:
"""
#1Sort####
##2Strategy######
CP: two pointers
RU: res = fast - slow
"""
###3Solve######
slow, fast, glo_max = 0, 0, 0
for fast in range(len(nums)):
if nums[fast] != 1: #stop
loc_max = fast -slow + 1
glo_max = max(glo_max, loc_max)
slow = fast
return max(loc_max, glo_max)
####4Check#########################
#[0, 0,1, 0, 1, 1]
我尝试并多次调试,将“slow”定义为Ones子数组的第一个索引,但未获得期望的结果。
您能否给出任何解决方案的提示?