Leetcode 31. Next Permutation (Medium) (cpp)

来源:互联网 发布:进口美工小号刀片 编辑:程序博客网 时间:2024/05/18 03:39

Leetcode 31. Next Permutation (Medium) (cpp)

Tag: Array

Difficulty: Medium


/*31. Next Permutation (Medium)Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).The replacement must be in-place, do not allocate extra memory.Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3 → 1,3,23,2,1 → 1,2,31,1,5 → 1,5,1*/class Solution {public:void nextPermutation(vector<int>& nums) {int i = nums.size() - 1, j = i; for (; i > 0; i--) {if (nums[i] > nums[i - 1]) {                break;            }        }if(i == 0) {sort(nums.begin(), nums.end());return;}for (; j > i; j--) {if (nums[j] > nums[i-1]) break;        }swap(nums[i-1], nums[j]);sort(nums.begin() + i, nums.end());}};class Solution {public:void nextPermutation(vector<int>& nums) {next_permutation(nums.begin(), nums.end());  }};


0 0
原创粉丝点击