在我们系列的第二部分中,我们进入了解决编码访谈问题的最广泛的模式之一:滑动窗口。该技术对于优化涉及连续元素的子阵列或子字的问题非常有用,例如最大化总和,在序列中找到特定条件或使用字符串中的子字符串。
滑动窗口模式的概述
滑动窗口模式是一种使您可以有效地解决需要从较大数据集中考虑数据子集的问题(例如数组的子阵列或字符串的子字符串)。该技术并没有在每次移动窗口时都要重新计算子集,而是要保持运行的总或条件,从而在数据上滑动以最大程度地减少不必要的工作。
何时使用滑动窗口:问题涉及连续的子阵列或子字符串。
初始化了大小k的窗口。
窗口在整个数组中移动时,通过减去不再在窗口中的元素并添加进入窗口的新元素来实现滑动效果。
def max_sum_subarray(arr, k): # Initialize variables to store the maximum sum and the current window sum. max_sum = 0 window_sum = 0 # First, calculate the sum of the initial window (first 'k' elements). for i in range(k): window_sum = arr[i] # Set the max_sum to the initial window's sum. max_sum = window_sum # Now, slide the window across the array. # Start from the kth element and move until the end of the array. for i in range(k, len(arr)): # Slide the window by subtracting the element that is no longer in the window # (arr[i - k]) and adding the new element (arr[i]). window_sum = arr[i] - arr[i - k] # Update max_sum if the current window sum is greater than the previous max_sum. max_sum = max(max_sum, window_sum) # Return the maximum sum found. return max_sum
2。
动态滑动窗口
实现滑动窗口解决方案的步骤
定义窗口边界
def smallest_subarray_with_sum(arr, S): # Initialize variables: # window_sum: to store the sum of the current window. # min_length: to store the length of the smallest subarray found. # window_start: the starting index of the sliding window. window_sum = 0 min_length = float('inf') # Start with a large number to compare minimum lengths. window_start = 0 # Iterate over the array with window_end being the right boundary of the window. for window_end in range(len(arr)): # Add the current element to the window_sum. window_sum = arr[window_end] # While the current window's sum is greater than or equal to S: while window_sum >= S: # Calculate the current window size and update min_length if smaller. min_length = min(min_length, window_end - window_start 1) # Shrink the window from the left by removing the element at window_start. window_sum -= arr[window_start] # Move the start of the window to the right. window_start = 1 # If min_length was updated, return it; otherwise, return 0 (meaning no valid subarray was found). return min_length if min_length != float('inf') else 0设置一个初始条件
:对于固定的Windows,初始化第一个窗口的sum/product/product/条件。对于动态窗口,初始条件取决于问题的目标。 滑动窗口
:[2
模式:使用动态滑动窗口展开直到找到重复的字符,然后收缩窗口直到满足条件为止。
[2
:使用一个动态滑动窗口,该窗口扩展以找到有效的子阵列并合同以最小化其长度。
使用hashmap或用于动态窗口的设置:在处理substrings或unique元素时,请使用集合来跟踪窗口中的元素。
从蛮力开始,然后优化请关注第3部分!
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3