Advertisement
exmkg

Untitled

Aug 5th, 2024
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.75 KB | None | 0 0
  1. class Solution {
  2.     public int[] sortArrayByParityII(int[] A) {
  3.         int i = 0;
  4.         int j = 1;
  5.         int n = A.length;
  6.  
  7.         while (i < n && j < n) {
  8.             // Find the next odd integer at an even position.
  9.             while (i < n && A[i] % 2 == 0) {
  10.                 i += 2;
  11.             }
  12.    
  13.             // Find the next even integer at an odd position.
  14.             while (j < n && A[j] % 2 == 1) {
  15.                 j += 2;
  16.             }
  17.  
  18.             // If both found, swap them.
  19.             if (i < n && j < n) {
  20.                 swap(A, i, j);
  21.             }
  22.         }
  23.  
  24.         return A;
  25.     }
  26.  
  27.     private void swap(int[] A, int i, int j) {
  28.         int temp = A[i];
  29.         A[i] = A[j];
  30.         A[j] = temp;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement