Advertisement
exmkg

Untitled

Aug 5th, 2024
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. class Solution {
  2.     public void sortColors(int[] nums) {
  3.         // We want to insert 0s one-by-one into their positions
  4.         // starting from index 0.
  5.         int zeroInsertPos = 0;
  6.  
  7.         // We want to insert 2s one-by-one into their positions
  8.         // starting from the last index (nums.length - 1).
  9.         int twoInsertPos = nums.length - 1;
  10.        
  11.         // Initialize iterator.
  12.         int i = 0;
  13.        
  14.         // Everything to the right of twoInsertPos is rightfully
  15.         // filled with 2s. When iterator goes into the territory of
  16.         // 2s, stop.
  17.         while (i <= twoInsertPos) {
  18.             if (nums[i] == 0) {
  19.                 // If we see a 0, put it into its respective position,
  20.                 // i.e. we do swap(nums[zeroInsertPos], nums[i]).
  21.                 swap(nums, zeroInsertPos, i);
  22.                 zeroInsertPos++;
  23.                 i++;
  24.             } else if (nums[i] == 1) {
  25.                 // If we see a 1, just leave it to be where it is.
  26.                 i++;
  27.             } else { // nums[i] == 2
  28.                 // If we see a 2, put it into its respective position,
  29.                 // i.e. we do swap(nums[i], nums[twoInsertPos]).
  30.                 swap(nums, i, twoInsertPos);
  31.                 twoInsertPos--;
  32.                 // Don't advance i to (i + 1) because if nums[i] AFTER SWAP
  33.                 // equals 0, then we should put that 0 to its respective position,
  34.                 // so don't advance yet – wait until the next iteration on i.
  35.             }
  36.         }
  37.     }
  38.  
  39.     private void swap(int[] nums, int i, int j) {
  40.         int temp = nums[i];
  41.         nums[i] = nums[j];
  42.         nums[j] = temp;
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement