Partition Array by Odd and Even

Question

Partition an integers array into odd number first and even number second.

Thought

Use the two pointer method to solve this problem:

  1. Set a start pointer and an end pointer.
  2. Move this two pointer to the middle until they are the same. Swap the item if necessary.

Code

class Solution:
    # @param nums: a list of integers
    # @return: nothing
    def partitionArray(self, nums):
        # write your code here
        start_index = 0
        end_index = len(nums) - 1
        while end_index > start_index:
            item_start = nums[start_index]
            item_end = nums[end_index]
            if item_start % 2 == 1:
                start_index += 1
            elif item_end % 2 == 0:
                end_index -= 1
            else:
                nums[start_index], nums[end_index] = item_end, item_start
                start_index += 1

results matching ""

    No results matching ""