1.双 list 遍历存储
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
tmp1 = []
tmp2 = []
for i in nums:
if i % 2 == 0:
tmp1.append(i)
else:
tmp2.append(i)
res = tmp2 + tmp1
return res
2. 首尾双指针
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
head, tail = 0, len(nums) - 1
while head < tail:
while head < tail and nums[head] % 2 == 1:
head += 1
while head < tail and nums[tail] % 2 == 0:
tail -= 1
nums[head], nums[tail] = nums[tail], nums[head]
return nums
这篇博客介绍了两种在Python中交换列表元素的方法。第一种是使用两个辅助列表,分别存储偶数和奇数索引的元素,然后合并得到交换后的列表。第二种方法运用了双指针技巧,从头尾开始遍历,交换不同奇偶性的元素,直至头尾指针相遇。这两种方法都有效地实现了列表元素的原地交换,避免了额外的空间开销。

被折叠的 条评论
为什么被折叠?



