Advertisement
epsilon413

next permutation

Jun 26th, 2024
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | Source Code | 0 0
  1. class Solution {
  2. public:
  3.     void nextPermutation(vector<int>& nums) {
  4.         // Find the anchor where a[i] < a[i+1]
  5.         int anchor = -1;
  6.         int n = nums.size();
  7.  
  8.         for(int i = 0; i < n - 1; i++) {
  9.             if(nums[i] < nums[i+1]) anchor = i;
  10.         }
  11.  
  12.         if(anchor == -1) {
  13.             // That means the array is sorted in increasing fashion,
  14.             // reverse the array
  15.             return std::reverse(nums.begin(), nums.end());
  16.         }
  17.  
  18.         // After finding the anchor index, find the next greater
  19.         // element than anchor, by traversing through the end to start
  20.         for(int i = n-1; i > anchor; i--) {
  21.             if(nums[i] > nums[anchor]) {
  22.                 // Swap the anchor element and the next greater
  23.                 int temp = nums[anchor];
  24.                 nums[anchor] = nums[i];
  25.                 nums[i] = temp;
  26.                 break;
  27.             }
  28.         }
  29.         return std::reverse(nums.begin() + anchor + 1, nums.end());
  30.     }
  31. };
Tags: leetcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement