Leetcode 刷题笔记 double pointers
双指针(核心思想)
- start, end 头尾两个指针相向移动进行数组的搜索
- 通常用于有序数组的搜索或排序
- 变体:快慢指针(链表找环)
167. Two Sum II - Input Array Is Sorted (medium)
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l = len(numbers)
left = 0
right = l-1
while left < right :
if (numbers[left] + numbers[right]) == target:
return [left+1,right+1];
elif numbers[left]+numbers[right] < target :
left += 1
else:
right -= 1
return 0
88. Merge Sorted Array (easy)
https://leetcode.com/problems/merge-sorted-array/
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
pos = m+n-1
l = m-1
r = n-1
while l >= 0 and r >= 0:
if nums1[l] >= nums2[r]:
nums1[pos] = nums1[l]
pos -= 1
l -=1
else:
nums1[pos] = nums2[r]
pos -= 1
r -= 1
while r > 0:
nums1[pos] = nums2[r]
pos -= 1
r -= 1
*** 两个数组 >>> 三指针(有一个pos指针用来定位)
(two sum变体)633. Sum of Square Numbers (medium)
https://leetcode.com/problems/sum-of-square-numbers/
class Solution:
def judgeSquareSum(self, c: int) -> bool:
a = 0
b = int(sqrt(c))
while a <= b:
if a*a + b*b == c:
return True
elif a*a + b*b > c:
b -= 1
else:
a += 1
return False
167 变体
(two sum变体)680. Valid Palindrome II (easy)
https://leetcode.com/problems/valid-palindrome-ii/
class Solution:
def validPalindrome(self, s: str) -> bool:
def ispalindrome(s, l , r):
while l < r:
if s[l] == s[r]:
l += 1
r -= 1
else:
return False
return True
l = 0
r = len(s) - 1
while l < r:
if s[l] == s[r]:
l += 1
r -= 1
else:
return ispalindrome(s, l+1, r) or ispalindrome(s, l , r-1)
return True
*** 直接遍历会超时,index也会爆 (后续需要进一步研究)***
Time complexity: O(n)
167变体
(88变体)524. Longest Word in Dictionary through Deleting (medium)
https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
l = 0
r = 0
rst = ''
dictionary.sort()
dictionary.sort(key = lambda x : len(x), reverse = True)
for key in dictionary:
while l < len(s) and r < len(key):
if s[l] == key[r]:
r += 1
l += 1
if r == len(key):
rst = key
return rst
elif l == len(s):
l = 0
r = 0
return ''
88的变体
快慢指针 142. Linked List Cycle II (medium)
https://leetcode.com/problems/linked-list-cycle-ii/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast =head
slow =head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
else:
return None
while fast != head:
head = head.next
fast = fast.next
return fast
双指针变体 >>> 滑动窗口:
https://blog.csdn.net/Gowott/article/details/123046130?spm=1001.2014.3001.5501