Untitled

 avatar
unknown
plain_text
5 months ago
1.3 kB
4
Indexable
public class SortArrayByParity {
    public static int[] sortArrayByParityII(int[] nums) {
        int n = nums.length;
        int evenIndex = 0; // Start at even index
        int oddIndex = 1;  // Start at odd index

        while (evenIndex < n && oddIndex < n) {
            // Check if evenIndex contains an odd number
            if (nums[evenIndex] % 2 == 1) {
                // Swap nums[evenIndex] and nums[oddIndex]
                int temp = nums[evenIndex];
                nums[evenIndex] = nums[oddIndex];
                nums[oddIndex] = temp;
            }
            // Move evenIndex if the number is already even
            if (nums[evenIndex] % 2 == 0) {
                evenIndex += 2;
            }
            // Move oddIndex if the number is already odd
            if (nums[oddIndex] % 2 == 1) {
                oddIndex += 2;
            }
        }
        return nums;
    }

    public static void main(String[] args) {
        int[] nums1 = {4, 2, 5, 7};
        int[] result1 = sortArrayByParityII(nums1);
        System.out.println(Arrays.toString(result1)); // Output: [4, 5, 2, 7]

        int[] nums2 = {2, 3};
        int[] result2 = sortArrayByParityII(nums2);
        System.out.println(Arrays.toString(result2)); // Output: [2, 3]
    }
}
Editor is loading...
Leave a Comment