Advertisement
exmkg

4-5

Jan 14th, 2025
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. class Solution {
  2.     public void sortColors(int[] nums) {
  3.         int pos = 0;
  4.         // The array will have 3 blocks: [zeros, ones, twos].
  5.         // 1. Move all 0s to the beginning of the array (to form `zeros` block).
  6.         for (int i = 0; i < nums.length; i++) {
  7.             if (nums[i] < 1) swap(nums, i, pos++);
  8.         }
  9.         // 2. pos points at the beginning of `ones` block –
  10.         //    move all 1s to the `ones` block.
  11.         for (int i = pos; i < nums.length; i++) {
  12.             if (nums[i] == 1) swap(nums, i, pos++);
  13.         }
  14.         // We don't need to do anything else since `zeros` and `ones` blocks
  15.         // are formed, which means `twos` block is already formed as well.
  16.     }
  17.  
  18.     private void swap(int[] nums, int i, int j) {
  19.         int temp = nums[i];
  20.         nums[i] = nums[j];
  21.         nums[j] = temp;
  22.     }
  23. }
  24.  
  25.  
  26.  
  27. class Solution {
  28.     public void sortColors(int[] nums) {
  29.         int[] freq = new int[3];
  30.         for (int x : nums) {
  31.             freq[x]++;
  32.         }
  33.         for (int x = 0, i = 0; x <= 2; x++) {
  34.             while (freq[x]-- > 0) {
  35.                 nums[i++] = x;
  36.             }
  37.         }
  38.     }
  39. }
  40.  
  41.  
  42.  
  43. class Solution {
  44.     public void sortColors(int[] nums) {
  45.         int zerosPosition = 0;
  46.         int ones = 0;
  47.         for (int i = 0; i < nums.length; i++) {
  48.             if (nums[i] == 0) nums[zerosPosition++] = 0;
  49.             else if (nums[i] == 1) ones++;
  50.         }
  51.         for (int i = zerosPosition; i < nums.length; i++) {
  52.             nums[i] = i < zerosPosition + ones ? 1 : 2;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement