数据结构之滑动窗口
双指针:在一个数组中同时从前往后走,一个快,一个慢
什么时候移动那个指针;找一个合法的窗口,怎么定义一个合法的窗口,什么时候打破,如何打破。
一、Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates such that each element appear only once and return the new length.
1 def remove_duplicate(nums): 2 i, j = 0, 1 3 while j < len(nums): 4 if nums[i] != nums[j]: 5 i += 1 6 nums[i] = nums[j] 7 j += 1 8 return nums[:i+1] 9 def removeDuplicates(nums): 10 if not nums: 11 return 0 12 tail = 0 13 for j in range(1, len(nums)): 14 if nums[tail] != nums[j]: 15 tail += 1 16 nums[tail] = nums[j] 17 return nums[:tail+1]
进阶:重复数字最多出现两次
1 # 思路一:跟前面两个比 2 def removeDuplicates(nums): 3 prev = 1 4 cur = 2 5 while cur < len(nums): 6 if nums[prev - 1] == nums[prev] and nums[prev] == nums[cur]: 7 cur += 1 8 else: 9 prev += 1 10 nums[prev] = nums[cur] 11 cur += 1 12 return nums[:prev+1] 13 # 思路二:跟前面第二个元素比 14 def remove_Duplicates(nums): 15 tail = 1 16 cur = 2 17 while cur < len(nums): 18 if nums[cur] == nums[tail - 1]: 19 cur += 1 20 else: 21 tail += 1 22 nums[tail] = nums[cur] 23 cur += 1 24 return nums[:tail+1]
# 思路二的另一种写法:
def removeDuplicates(nums):
count = 0
for i in range(len(nums)):
if count < 2 or nums[count - 2] != nums[i]:
nums[count] = nums[i]
count += 1
return nums[:count]
二、Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
1 def removeElement(nums, val): 2 i = 0 3 j = 0 4 while j < len(nums): 5 if nums[j] == val: 6 j += 1 7 else: 8 nums[i] = nums[j]#缺点:有很多多余的赋值操作 9 j += 1 10 i += 1 11 return i
1 def removeElement2(nums, val): 2 start, end = 0, 0 3 while start <= end: 4 if nums[start] == val: 5 nums[start], nums[end] = nums[end], nums[start] 6 end -= 1 7 else: 8 start += 1 9 return start
三、Maximum Average Subarray
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value
Assume 1 <= k <= n
直接sum/slice,每次移动窗口都计算一次:O(kn)
可以用accumulate
1 def findMaxnumsaverage(nums, k): 2 p = [0] 3 for x in nums: 4 p.append(p[-1] + x) 5 moving_sum = max(p[i+k] - p[i] for i in range(len(nums)-k+1)) 6 return moving_sum / float(k) 7 8 from itertools import accumulate 9 def findMax(nums, k): 10 t = [0] 11 t.extend(nums) 12 tmp = list(accumulate(t)) 13 moving_sum = max(tmp[i + k] - tmp[i] for i in range(len(nums) - k + 1)) 14 return moving_sum / float(k)
1 def find_max(nums, k): 2 moving_sum = 0.0 3 for i in range(k): 4 moving_sum += nums[i] 5 res = moving_sum 6 for i in range(k, len(nums)): 7 moving_sum = moving_sum + nums[i] - nums[i - k] 8 res = max(res, moving_sum) 9 return res/k
进阶:求max
四、Longest Continuous Increasing Sunsequence
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
1 def findLongest(nums): 2 result, count = 0, 0 3 for i in range(len(nums)): 4 if i == 0 or nums[i - 1] < nums[i]: 5 count += 1 6 result = max(result, count) 7 else: 8 count = 1 9 return result
五、Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead
Given the array [2,3,1,2,4,3] and s = 7
the subarray [4,3] has the minimal length under the problem constraint
1 #什么时候是一个invalid的窗口,什么时候是一个valid的窗口 2 #invalid-->valid j+ valid--> i-打破 O(n) 3 import sys 4 def minsubarray(nums, target): 5 i = j = sum = 0 6 count = sys.maxsize 7 while j < len(nums): 8 sum += nums[j] 9 j += 1 10 while sum > target: 11 count = min(j - i, count) 12 sum -= nums[i] 13 i += 1 14 return 0 if count == sys.maxsize else count
什么时候移动i,什么时候移动j-->基本上有两个while循环,一个是while j<len, 第二个是当找到一个好窗口的时候,需要去打破它,while condition 打破窗口
六、Implement strStr() ************
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1 def solution(s1, s2): #O(mn) 2 if len(s1) < len(s2): 3 return None 4 i = 0 5 while i < len(s1) - len(s2) + 1: 6 j = 0 7 k = i 8 while j < len(s2): 9 if s1[k] == s2[j]: 10 k += 1 11 j += 1 12 else: 13 break 14 if j == len(s2): 15 break 16 else: 17 i += 1 18 if i == len(s1) - len(s2) + 1: 19 return None 20 else: 21 return s1[i:]
1 # 2 class Solution: 3 def strStr(self, haystack: str, needle: str) -> int: 4 if needle is '': 5 return 0 6 if len(needle) > len(haystack): 7 return -1 8 i = 0 9 while i < len(haystack) - len(needle) + 1: 10 j = 0 11 while j < len(needle) and needle[j] == haystack[i + j]: 12 if j == len(needle) - 1: 13 return i 14 j += 1 15 i += 1 16 return -1
七、Subarray Product Less Than K
Your are given an array of positive integers nums
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k
1 def solution(nums, target): 2 i = 0 3 count = 0 4 while i < len(nums): 5 mul = nums[i] 6 j = i 7 while j < len(nums) and mul < target: 8 count += 1 9 j += 1 10 if j < len(nums): 11 mul = mul * nums[j] 12 i += 1 13 return count
1 def numSubarrayProductLessThanK(nums, k): 2 product = 1 3 i = 0 4 ans = 0 5 for j, num in enumerate(nums): 6 product *= num 7 while product >= k: 8 product /= nums[i] 9 i += 1 10 ans += (j - i + 1) 11 return ans

浙公网安备 33010602011771号