目录:
- Two Sum II
- Sort Colors
- 盛最多水的容器
知识点:双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。
167. Two Sum II - Input array is sorted
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
start=0
end=len(numbers)-1
while start<end:
if numbers[start]+numbers[end]==target:
return start+1,end+1
if numbers[start]+numbers[end]<target:
start+=1
else:
end-=1
return None
75. Sort Colors
荷兰国旗问题:
解题思路:创建一个head 和tail指针指向数组的头和尾,遍历数组,如果是0则和head 指向的元素交换;如果是1则和tail指针指向的元素交换。同时移动相应的指针位置。
代码:
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
head,cur,tail=0,0,len(nums)-1
while cur <= tail:
if nums[cur]==0:
nums[head],nums[cur]=nums[cur],nums[head]
head+=1
cur+=1
elif nums[cur]==2:
nums[cur],nums[tail]=nums[tail],nums[cur]
tail-=1
else:
cur+=1
return nums
11. 盛最多水的容器
代码:
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
left = 0
right = len(height) - 1
maxArea = 0
while left < right:
b = right - left
if height[left] < height[right]:
h = height[left]
left += 1
else:
h = height[right]
right -= 1
area = b*h
if maxArea < area:
maxArea = area
return maxArea