LeetCode——031

来源:互联网 发布:下载软件 支持thunder 编辑:程序博客网 时间:2024/06/05 15:45

这里写图片描述
/*
31. Next Permutation My Submissions QuestionEditorial Solution
Total Accepted: 63632 Total Submissions: 240911 Difficulty: 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,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
Subscribe to see which companies asked this question
*/
/*
解题思路:
//方法一:使用STL
//方法二:
从后往前找,找到第一个左(i-1)>右(i)的点,然后在从后找,找到第一个大于nums[i-1]的值nums[j],然后交换两个值。最后一步把i-1位置之后改为降序(只要reverse就可以了,因为原来就是升序)
*/

class Solution {public:    void nextPermutation(vector<int>& nums) {        //调用stl        //  next_permutation(nums.begin(),nums.end());       //自己写       int i,j;       for( i=nums.size()-1;i>0;i--){           if(nums[i]>nums[i-1])break;       }       //已经排好序了       if(i==0){           reverse(nums.begin(),nums.end());           return ;       }       //找到第一个比nums[i-1]大的数,然后进行交换       for(j=nums.size()-1;j>i-1;j--){           if(nums[j]>nums[i-1]){               swap(nums[j],nums[i-1]);               //交换完后把i-1后面的所有元素反转               reverse(nums.begin()+i,nums.end());               break;           }       }    }};
0 0
原创粉丝点击