Leetcode - 922 Sorting By Parity 2

107 Views Asked by At

Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition.

I've written this code.

public static void main(String[] args) {
        int[] nums = {1,3,5,7,2,4,6,8};
        int[] res = new int[nums.length]; 
        int a=0;
        int b=0;
        int c=1;
        while (a < nums.length && b < nums.length+1 && c < nums.length+1){
            if (nums[a]%2 == 0){
                res[b] = nums[a];
                a++;
                b += 2;
            }
            if (nums[a]%2 != 0){
                res[c] = nums[a];
                a++; 
                c += 2;
            }
        }
        for (int i : res){
            System.out.println(res[i]);
        }
        System.out.println();
    }

While executing the {1,3,5,7,2,4,6,8} in even spaces it fills '0' but, while executing the {2,4,6,8,10,1,3,5,7,9} it gives correct answer. Can someone please help me here?

1

There are 1 best solutions below

3
Maurice Perry On

Because it in the first case, your code puts the odd numbers in the res array, and then stops because of the c < nums.length+1 condition. You only need a < nums.length as while condition.