LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  void nextPermutation(vector<int>& nums) {
    next_permutation(begin(nums), end(nums));
  }
};
23541 => 找到 3 < 5 => 排序 3 右侧
23145 =>  3 与右侧第一个大于 3 的数交换
24135

54321 => 找不到则说明无下一排列,翻转即可
class Solution {
 public:
  void nextPermutation(vector<int>& nums) {
    if (size(nums) <= 1) {
      return;
    }
    for (int i = size(nums) - 1; i > 0; --i) {
      if (nums[i - 1] < nums[i]) {
        sort(begin(nums) + i, end(nums));
        for (int j = i; j < size(nums); ++j) {
          if (nums[j] > nums[i - 1]) {
            swap(nums[i - 1], nums[j]);
            return;
          }
        }
      }
    }
    reverse(begin(nums), end(nums));
  }
};