知識點:雙指針主要用於遍歷數組,兩個指針指向不同的元素,從而協同完成任務。
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