第 13 天
双指针 Two-pointer Tech
left指针指向list开头,right指向list结尾,且left为偶数指针,right为奇数指针,遍历list若left指向偶数,left指向奇数,则交换两指针指向的数字,直到两指针相遇。
时间复杂度O(n), 空间复杂度O(1)。
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
n = len(nums)
left = 0
right = n-1
while left<right:
if nums[left]%2 != 0:
left += 1
elif nums[right]%2 != 1:
right -= 1
elif nums[left]%2 == 0 and nums[right]%2 == 1:
nums[left],nums[right] = nums[right],nums[left]
right -= 1
left += 1
return nums
这个题比较简单了,设置left和right一个开头一个结尾,两个数和大于target则right-1,两个数和小于target则left+1
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i, j = 0, len(nums) - 1
while i < j:
s = nums[i] + nums[j]
if s > target: j -= 1
elif s < target: i += 1
else: return nums[i], nums[j]
return []
先贴上我的代码再总结代码里用到的知识点
class Solution:
def reverseWords(self, s: str) -> str:
s = re.sub(' +', ' ', s).strip().split()
n = len(s)
left = 0
right = n-1
while left<right:
s[left],s[right] = s[right],s[left]
left += 1
right -= 1
return ' '.join(s)
首先是re.sub(' +', ' ', s)的用法,它的功能是将str中大于一个位的空格全部变成一个位的空格,str.strip()的用法是去除掉str两边的空格,split()是通过空格将str变成一个一个单词的list,因为python中list是可变数据结构,下面调换位置需要在可变数据结构上操作,而str是不可变数据结构,接下来就是左右指针调换位置了