解决力扣:
配合b站视频讲解食用更佳:https://www.bilibili.com/video/BV1vW4y1P7V7
核心提示:好几道题是处理有序数组的!
344.反转字符串
from typing import List
# @lc code=start
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left,right = 0, len(s)-1
while(left<right):
left_char = s[left]
right_char = s[right]
s[left] = right_char
s[right] = left_char
left+=1
right-=1
167:
有序数组,
from typing import List
# @lc code=start
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left,right = 0, len(numbers) - 1
while left < right:
# 因为有序,可以小了左指针向右移动
if numbers[left] + numbers[right] < target:
left += 1
# 大了右指针向左移动
elif numbers[left] + numbers[right] > target:
right-=1
# 注意题目要求的返回值从1开始编号
else:
return [left+1,right+1]
return [-1,-1]
# @lc code=end
26 删除有序数组中的重复元素
# @lc code=start
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# 空值则不用删除
if len(nums) == 0:
return 0
# 定义快慢指针
slow,fast = 0,0
# 只要快指针没越界,就继续往前走
while fast < len(nums):
if nums[fast]!=nums[slow]: # 不相等时慢指针需要+1
slow+=1
# 维护nums[0..slow]无重复
nums[slow] = nums[fast]
fast+=1
# 返回的是唯一值的个数,也就是slow+1
return slow+1
27.移除元素
from typing import List
# @lc code=start
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
fast,slow = 0,0
while fast<len(nums):
if nums[fast] !=val:
nums[slow] = nums[fast]
slow +=1
fast+=1
return slow
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# step1:用快慢双指针把非0的按顺序排好
slow,fast = 0,0
while fast < len(nums):
if nums[fast]!=0:
nums[slow] = nums[fast]
slow+=1
fast+=1
# 最后几个补0操作 range是左闭右开的, 19行slow+1,所以不会覆盖
# 若全是0 则16行的while一次都没调用,全部补0, 从[0,len(nums)) 也是对的
for i in range(slow,len(nums)):
nums[i] = 0