Advertisement
exmkg

Untitled

Aug 15th, 2024
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. class Solution {
  2.     public void nextPermutation(int[] nums) {
  3.         // 1 2 3
  4.         // 1 3 2
  5.         // 2 1 3
  6.         // 2 3 1
  7.        
  8.         // 1 2 3 4
  9.         // 1 2 4 3
  10.         // 1 3 2 4
  11.         // 1 3 4 2
  12.         // 1 4 2 3
  13.  
  14.         // i-1 i   j
  15.         // 2 1 3 4
  16.         //
  17.         //
  18.        
  19.        
  20.         // i-1 i j
  21.         // 3 1 2 4
  22.  
  23.  
  24.  
  25.         // 2 1 3 4
  26.         // 2 1 4 3
  27.         // 2 3 1 4
  28.         // 2 3 4 1
  29.         // 2 4 1 3
  30.         // 2 4 3 1
  31.         // 3 1 2 4
  32.         // ...
  33.  
  34.         // i-1 i
  35.         //     j
  36.         // 3 4 2 1
  37.  
  38.         //
  39.        
  40.         //   i
  41.         // 4 3 2 1
  42.  
  43.         int n = nums.length;
  44.        
  45.         // We are going to find the leftmost i such that
  46.         // nums[i] >= nums[i + 1] >= ... >= nums[n - 1]
  47.         int i = n - 1;
  48.         while (i - 1 >= 0 && nums[i - 1] >= nums[i]) {
  49.             i--;
  50.         }
  51.  
  52.         // It means that the current permutation is
  53.         // the last possible permutation, so the next permutation
  54.         // is going to be the very first permutation (which is a ascendingly sorted array).
  55.         if (i == 0) {
  56.             // Simply, reverse the array.
  57.             Arrays.sort(nums);
  58.             return;
  59.         }
  60.  
  61.         // j is going to be the index of the next greater number than nums[i - 1].
  62.         int j = -1;
  63.         for (int k = i; k < n; k++) {
  64.             if (nums[k] > nums[i - 1] && (j == -1 || nums[k] <= nums[j])) {
  65.                 j = k;
  66.             }
  67.         }
  68.  
  69.         // swap(nums[i - 1], nums[j]);
  70.         int t = nums[i - 1];
  71.         nums[i - 1] = nums[j];
  72.         nums[j] = t;
  73.  
  74.         // reverse(nums, i, n - 1);
  75.         for (int left = i, right = n - 1; left < right; left++, right--) {
  76.             // swap(nums[left], nums[right]);
  77.             t = nums[left];
  78.             nums[left] = nums[right];
  79.             nums[right] = t;
  80.         }
  81.     }
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement