Algorithm in LeetCode —— Two Pointers

Two Pointers 的 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)
	}
  • 快慢指针可以查找重复数字,时间复杂度 O(n),第 287 题。
  • 替换字母以后,相同字母能出现连续最长的长度。第 424 题。
  • SUM 问题集。第 1 题,第 15 题,第 16 题,第 18 题,第 167 题,第 923 题,第 1074 题。
TitleSolutionDifficultyTimeSpace收藏
3. Longest Substring Without Repeating CharactersGoMediumO(n)O(1)❤️
11. Container With Most WaterGoMediumO(n)O(1)
15. 3SumGoMediumO(n^2)O(n)❤️
16. 3Sum ClosestGoMediumO(n^2)O(1)❤️
18. 4SumGoMediumO(n^3)O(n^2)❤️
19. Remove Nth Node From End of ListGoMediumO(n)O(1)
26. Remove Duplicates from Sorted ArrayGoEasyO(n)O(1)
27. Remove ElementGoEasyO(n)O(1)
28. Implement strStr()GoEasyO(n)O(1)
30. Substring with Concatenation of All WordsGoHardO(n)O(n)❤️
42. Trapping Rain WaterGoHardO(n)O(1)❤️
61. Rotate ListGoMediumO(n)O(1)
75. Sort ColorsGoMediumO(n)O(1)❤️
76. Minimum Window SubstringGoHardO(n)O(n)❤️
80. Remove Duplicates from Sorted Array IIGoMediumO(n)O(1
86. Partition ListGoMediumO(n)O(1)❤️
88. Merge Sorted ArrayGoEasyO(n)O(1)❤️
125. Valid PalindromeGoEasyO(n)O(1)
141. Linked List CycleGoEasyO(n)O(1)❤️
142. Linked List Cycle IIGoMediumO(n)O(1)❤️
167. Two Sum II - Input array is sortedGoEasyO(n)O(1)
209. Minimum Size Subarray SumGoMediumO(n)O(1)
234. Palindrome Linked ListGoEasyO(n)O(1)
283. Move ZeroesGoEasyO(n)O(1)
287. Find the Duplicate NumberGoEasyO(n)O(1)❤️
344. Reverse StringGoEasyO(n)O(1)
345. Reverse Vowels of a StringGoEasyO(n)O(1)
349. Intersection of Two ArraysGoEasyO(n)O(n)
350. Intersection of Two Arrays IIGoEasyO(n)O(n)
424. Longest Repeating Character ReplacementGoMediumO(n)O(1)
524. Longest Word in Dictionary through DeletingGoMediumO(n)O(1)
532. K-diff Pairs in an ArrayGoEasyO(n)O(n)
567. Permutation in StringGoMediumO(n)O(1)❤️
713. Subarray Product Less Than KGoMediumO(n)O(1)
763. Partition LabelsGoMediumO(n)O(1)❤️
826. Most Profit Assigning WorkGoMediumO(n log n)O(n)
828. Unique Letter StringGoHardO(n)O(1)❤️
838. Push DominoesGoMediumO(n)O(n)
844. Backspace String CompareGoEasyO(n)O(n)
845. Longest Mountain in ArrayGoMediumO(n)O(1)
881. Boats to Save PeopleGoMediumO(n log n)O(1)
904. Fruit Into BasketsGoMediumO(n log n)O(1)
923. 3Sum With MultiplicityGoMediumO(n^2)O(n)
925. Long Pressed NameGoEasyO(n)O(1)
930. Binary Subarrays With SumGoMediumO(n)O(n)❤️
977. Squares of a Sorted ArrayGoEasyO(n)O(1)
986. Interval List IntersectionsGoMediumO(n)O(1)
992. Subarrays with K Different IntegersGoHardO(n)O(n)❤️
1004. Max Consecutive Ones IIIGoMediumO(n)O(1)
1093. Statistics from a Large SampleGoMediumO(n)O(1)