【滑动窗口】1004. 最大连续1的个数 III
发布人:shili8
发布时间:2025-03-08 21:05
阅读次数:0
**滑动窗口**
在计算机科学中,滑动窗口是一种常见的算法技术。它涉及到维护一个固定大小的窗口,通过不断地向前移动这个窗口来处理数据序列。
**最大连续1的个数 III**
今天,我们要解决的一个问题是:给定一个二进制数组 `nums`,请找出其中最长的连续1 的组合。具体来说,我们需要返回该组合中1 的数量。
例如,如果输入数组 `[1,1,0,1,1,1]`,则输出应该为 `5`,因为连续1 的最大组合是 `[1,1,1]`,长度为 `3`。
**解决方案**
我们可以使用滑动窗口技术来解决这个问题。具体来说,我们会维护一个窗口,包含当前最长的连续1 的组合。
def findMaxLength(nums): """ Finds the maximum length of a contiguous sequence of1's in the given binary array. Args: nums (list): A list of binary integers. Returns: int: The maximum length of a contiguous sequence of1's. """ max_length =0 window_start =0 # Initialize the count of1's and0's in the current window ones_in_window =0 zeros_in_window =0 for window_end in range(len(nums)): if nums[window_end] ==1: ones_in_window +=1 else: zeros_in_window +=1 # If the count of1's and0's is equal, we have found a valid window while ones_in_window != zeros_in_window: if nums[window_start] ==1: ones_in_window -=1 else: zeros_in_window -=1 window_start +=1 # Update the maximum length of a contiguous sequence of1's max_length = max(max_length, ones_in_window + zeros_in_window) return max_length
**示例**
print(findMaxLength([1,1,0,1,1,1])) # Output:5print(findMaxLength([0,0,1,1,0,1,1])) # Output:4print(findMaxLength([1,1,1,1,1,1,1,1])) # Output:8
**注释**
* 我们维护一个窗口,包含当前最长的连续1 的组合。
* 每当我们遇到一个新的数字时,我们都会更新窗口内的1 和0 的计数。
* 如果窗口内的1 和0 的计数相等,我们就有找到一个有效的窗口了。
* 我们不断地向前移动窗口,直到我们找到了最长的连续1 的组合。
**时间复杂度**
* 时间复杂度为 O(n),其中 n 是输入数组的长度。