剑指 Offer 21. 调整数组顺序使奇数位于偶数前面(Easy);
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
# 两个List存
Ji = []
Ou = []
for i in nums :
if i%2 != 0 :
Ji.append(i)
else :
Ou.append(i)
return Ji + Ou
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
# 对撞双指针
ret = [0 for _ in nums]
left,right = 0 , len(nums)-1
for i in range(len(nums)):
if nums[i]%2 !=0 :
ret[left] = nums[i]
left+=1
else :
ret[right] = nums[i]
right-=1
return ret
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
# 快慢指针
# 慢指针存最后一个奇数位置,快指针搜索下一个奇数位置
fast,slow = 0 , 0
while fast < len(nums):
if nums[fast]%2 != 0 :
nums[slow] , nums[fast] = nums[fast] ,nums[slow]
slow+=1
fast+=1
return nums
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# 倒序快慢指针
fast , low = len(nums) -1, len(nums)-1
while fast >= 0 :
if nums[fast] == val:
nums[low],nums[fast] =nums[fast],nums[low]
low-=1
fast-=1
return low+1
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]=nums[fast],nums[slow]
slow+=1
fast+=1
return slow
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
# 双指针
# name → N1
# typed →N2
N1,N2 = 0,0
while N1<len(name) and N2<len(typed) :
if name[N1]==typed[N2]:
N1+=1
N2+=1
elif N2>0 and typed[N2] == typed[N2-1]:
N2+=1
else :
return False
while N2<len(typed) and typed[N2]==typed[N2-1]:
N2+=1
if N1 == len(name) and N2 == len(typed):
return True
else:
return False
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
# 双指针 -- 看完题解简化版本
# name → N1
# typed →N2
N1 , N2 = 0 , 0
while N2 < len(typed): # 这里只考虑N2 是因为若返回True 则必须 N2>=N1
if N1<len(name) and name[N1]==typed[N2] : # 防止N1溢出,当二者相等,均+1
N1 += 1
N2 += 1
elif N2>0 and typed[N2]==typed[N2-1]: # 考虑跟上一个相等的时候,要考虑List仅有一个数时候[0] ==[0-1]
N2 +=1
else :
return False
return N1 == len(name) #防止出现 len(name) > len(typed)出现