题目
【代码】
【方法1】不需要额外空间,双指针原地操作
执行用时:48 ms, 在所有 Python3 提交中击败了56.77% 的用户
内存消耗:19.3 MB, 在所有 Python3 提交中击败了12.68% 的用户
通过测试用例:17 / 17
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
left,right=0,len(nums)-1
while left<right:
while left<len(nums) and nums[left]%2==1:
left+=1
while right>=0 and nums[right]%2==0:
right-=1
if left<right:
nums[left],nums[right]=nums[right],nums[left]
else:
return nums
return nums
【方法2:双指针-首尾指针】
空间复杂度较高 需要申请O(n)的空间
执行用时:52 ms, 在所有 Python3 提交中击败了36.71% 的用户
内存消耗:19.5 MB, 在所有 Python3 提交中击败了7.24% 的用户
通过测试用例:17 / 17
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
ans=[-1]*len(nums)
left,right=0,len(nums)-1
for idx in range(len(nums)):
if nums[idx]%2==1:
ans[left]=nums[idx]
left+=1
else:
ans[right]=nums[idx]
right-=1
return ans
【方法3:双指针-快慢指针】
执行用时:56 ms, 在所有 Python3 提交中击败了21.85% 的用户
内存消耗:19.1 MB, 在所有 Python3 提交中击败了26.48% 的用户
通过测试用例:17 / 17
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
low,fast=0,0
while fast<len(nums):
if nums[fast]%2==1:
nums[low],nums[fast]=nums[fast],nums[low]
low+=1
fast+=1
return nums