Q: Partition Array by Odd and Even

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

Example

Given[1, 2, 3, 4], return[1, 3, 2, 4]

Note:

    public void partitionArray(int[] nums) {
        //corner case
        if(nums == null || nums.length == 0){
            return;
        }

        //Using two pointers : O(n)
        int L = 0;
        int R = nums.length - 1;
        while(L <= R){
            while( L <= R && nums[L] % 2 == 1){
                L++;
            }
            while( L <= R && nums[R] % 2 == 0){
                R--;
            }

            if( L <= R && nums[L] %2 == 0 && nums[R] % 2 == 1){
                swap(nums, L, R);
                L++;
                R--;
            }
        }

    private void swap(int[] nums, int i, int j){
        if(i == j){ return;}
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

results matching ""

    No results matching ""