剣指Offer 21.奇数が偶数の前にあるように配列順序を調整します.

6634 ワード

整数配列を入力し、すべての奇数が配列の前半に位置し、すべての偶数が配列の後半に位置するように、配列内の数値の順序を調整する関数を実現します.
例:
入力:nums=[1,2,3,4]出力:[1,3,2,4]注:[3,1,2,4]も正しい答えの一つです.
ヒント:
1 <= nums.length <= 50000 1 <= nums[i] <= 10000
class Solution:
    def exchange(self, nums: List[int]) -> List[int]:
        len_nums = len(nums)
        start_index = 0
        end_index = len_nums - 1

        #           ,   ,   ,     ,     
        while end_index > start_index:
            start_index, end_index = self.is_exchange(nums, start_index, end_index)

        # print(nums)
        return nums  


    def is_exchange(self, nums, start_index, end_index):
        #         ,        ,     ,       ,     
        if (nums[start_index] & 1  == 0) and nums[end_index] & 1:
            # print(nums[start_index] & 1, nums[end_index] & 1, nums[end_index], nums[start_index])
            nums[start_index], nums[end_index] = nums[end_index], nums[start_index]
            start_index += 1
            end_index -= 1
        #      ,     ,        ,       
        elif nums[start_index] & 1 and nums[end_index] & 1:
            start_index += 1
        #      ,     ,        ,       
        elif nums[start_index] & 1 and (nums[end_index] & 1 == 0):
            start_index += 1
            end_index -= 1
        #      ,      ,        ,       
        elif (nums[start_index] & 1 == 0) and (nums[end_index] & 1 == 0):
            end_index -= 1

        return start_index,end_index