Algorithm in LeetCode —— Sliding Window

Sliding Window 的 Tips:

  • 双指针滑动窗口的经典写法。右指针不断往右移,移动到不能往右移动为止(具体条件根据题目而定)。当右指针到最右边以后,开始挪动左指针,释放窗口左边界。第 3 题,第 76 题,第 209 题,第 424 题,第 438 题,第 567 题,第 713 题,第 763 题,第 845 题,第 881 题,第 904 题,第 978 题,第 992 题,第 1004 题,第 1040 题,第 1052 题。
	left, right := 0, -1

	for left < len(s) {
		if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
			freq[s[right+1]-'a']++
			right++
		} else {
			freq[s[left]-'a']--
			left++
		}
		result = max(result, right-left+1)
	}
  • 滑动窗口经典题。第 239 题,第 480 题。
TitleSolutionDifficultyTimeSpace收藏
3. Longest Substring Without Repeating CharactersGoMediumO(n)O(1)❤️
76. Minimum Window SubstringGoHardO(n)O(n)❤️
239. Sliding Window MaximumGoHardO(n * k)O(n)❤️
424. Longest Repeating Character ReplacementGoMediumO(n)O(1)
480. Sliding Window MedianGoHardO(n * log k)O(k)❤️
567. Permutation in StringGoMediumO(n)O(1)❤️
978. Longest Turbulent SubarrayGoMediumO(n)O(1)❤️
992. Subarrays with K Different IntegersGoHardO(n)O(n)❤️
995. Minimum Number of K Consecutive Bit FlipsGoHardO(n)O(1)❤️
1004. Max Consecutive Ones IIIGoMediumO(n)O(1)
1040. Moving Stones Until Consecutive IIGoMediumO(n log n)O(1)❤️
1052. Grumpy Bookstore OwnerGoMediumO(n log n)O(1)
1074. Number of Submatrices That Sum to TargetGoHardO(n^3)O(n)❤️