我正在练习两种指针技术来解决Max Consecutive Ones - LeetCode
给出一个二进制数组,找到该数组中最大连续1个数。
示例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.
注意:
- 输入数组将仅包含
0
和1
。- 输入数组的长度是一个正整数,不会超过10,000
该解决方案使用Kadane算法
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时,关系为length= fast - slow
。
但是,很难找到指向第一个慢速指针的位置。 [0, 0, 0, 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]
我多次尝试调试以将慢速定义为Ones子数组的第一个索引,但未获得预期的结果。
请您提供有关该解决方案的任何提示。
答案 0 :(得分:1)
我认为您已经很接近了,这只是真正在观察索引相对于您更新长度的更新位置的问题。还有一些棘手的情况,例如[1]
,如果不正确的话会失败。
我发现使用while循环更容易做到这一点,因此我可以明确指出索引的更新位置。这是一种有效的方法:
def findMaxConsecutiveOnes(nums):
slow, fast, glo_max, loc_max = 0, 0, 0, 0
while fast < len(nums):
if nums[fast] == 0:
loc_max = fast - slow
glo_max = max(glo_max, loc_max)
slow = fast + 1 # need to add one more because we haven't incremented fast yet
fast += 1
loc_max = fast - slow # end check for cases that end with 1
return max(loc_max, glo_max)
findMaxConsecutiveOnes([1]) # 1
findMaxConsecutiveOnes([1, 1]) # 2
findMaxConsecutiveOnes([0, 1]) # 1
findMaxConsecutiveOnes([0, 1, 1, 0, 0, 1, 1, 1, 0]) # 3
这通过leet代码测试,但未设置任何速度记录。
答案 1 :(得分:0)
您可以尝试以下解决方案。 基本上你会跟踪计数,直到你达到 0,然后返回 maxCount。
ifneq ($(filter $(GCC_MINOR),4 5),)
echo "def"
endif
答案 2 :(得分:0)