0
点赞
收藏
分享

微信扫一扫

按奇偶排序数组II-双指针922-python

大雁f 2022-05-04 阅读 44

没看答案,运用双指针,找到不符合要求位置的奇数和偶数进行调换即可。

class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        n = len(nums)
        i, j = 0, 1

        while True:
            while i < n and nums[i] % 2 == 0:
                i += 2
            
            while j < n and nums[j] % 2 == 1:
                j += 2
            
            if i >= n and j >= n:
                break

            nums[i], nums[j] = nums[j], nums[i]
        
        return nums
举报

相关推荐

0 条评论