左右指针
主要解决的是数组、字符串的问题,比如二分查找
左右指针的实际就是 left = 0, right = len(nums) -1通过不断右移left和左移right知道left和right相遇为结束。
1、二分查找
二分查找框架
def binarySearch(int[] nums, int target) {
int left = 0, right = len(nums) -1;
while(left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid
} else if (nums[mid] < target) {
left = mid + 1
} else if (nums[mid] > target) {
right = mid -1
}
}
return -1;
}
2、两数之和
leetcode167 两数之和II
只要数组是有序的情况下,就可以想采用双指针的技巧
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left = 0
right = len(numbers) - 1
while left <= right:
count = numbers[left] + numbers[right]
if count == target:
return [left + 1,right + 1]
elif count > target:
right -= 1
elif count < target:
left += 1
return [-1,-1]
3、反转数组
leetcode344 反转字符串
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left = 0
right = len(s) -1
while left < right:
s[left],s[right] = s[right],s[left]
left += 1 #右移
right -= 1#左移