Advertisement
exmkg

3-2

Jan 14th, 2025
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. class Solution {
  2.     public int[] pivotArray(int[] nums, int pivot) {
  3.         int n = nums.length;
  4.  
  5.         int[] result = new int[n];
  6.         int insertPosition = 0;
  7.  
  8.         // The idea is that after partitioning,
  9.         // the array will be split into three blocks:
  10.         // [(numbers < pivot), (numbers == pivot), (numbers > pivot)].
  11.  
  12.         // Firstly, put all (numbers < pivot)
  13.         // at the beginning of the result array.
  14.         // Count the # of (numbers == pivot) in the process.
  15.         int pivotFreq = 0;
  16.         for (int num : nums) {
  17.             if (num < pivot) {
  18.                 result[insertPosition] = num;
  19.                 insertPosition++;
  20.             } else if (num == pivot) {
  21.                 pivotFreq++;
  22.             }
  23.         }
  24.        
  25.         // After all (numbers < pivot), we shall
  26.         // insert all pivots [now that we know the
  27.         // # of (numbers == pivot), it is easy to do].
  28.         while (pivotFreq > 0) {
  29.             result[insertPosition] = pivot;
  30.             insertPosition++;
  31.             pivotFreq--;
  32.         }
  33.        
  34.         // After that, insert the rest, i.e. all (numbers > pivot).
  35.         for (int num : nums) {
  36.             if (num > pivot) {
  37.                 result[insertPosition] = num;
  38.                 insertPosition++;
  39.             }
  40.         }
  41.        
  42.         return result;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement