[LeetCode]Next Permutation(!!!)

来源:互联网 发布:知乎 套路钓鱼 编辑:程序博客网 时间:2024/05/09 06:36

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

题目的意思是求下一个回文数,如果是最大的那个就变成最小的那个
首先我们考虑下从最大的数,变成最小的数,就是依次交换最高位和最低位。

其他情况比如 236541,我们从后往前寻找,找到第一个非递减的数,这里是3,然后从3开始往后寻找比3大的最小的数(实际上就是比3大的最后一个数,这里是4,将4和3交换后为246531然后将6531翻转即可241356

class Solution {public:    void nextPermutation(vector<int>& nums) {        int i = nums.size()-2;      //从非最后一个元素开始,找非递减的第一个数        int j;        while(nums[i]>=nums[i+1]&&i>=0){            --i;        }        if(i>=0){        //说明nums不是最大的那个数,则找比nums[i]大的最后一个数            j = i+1;            while(nums[j]>nums[i]&&j<nums.size())                ++j;            --j;    //回溯一个,则j为第一个比nums[i]大数            swap(nums[i],nums[j]);        }        reverse(nums,i+1);    }    void swap(int &a, int &b){        a = a ^ b;        b = a ^ b;        a = a ^ b;    }    void reverse(vector<int>& nums,int sta){//sta为翻转的起点        int l = sta;        int r = nums.size()-1;        while(l<r){            swap(nums[l],nums[r]);            ++l,--r;        }    }};

这里的reverse是自己写的,当然也可以调用系统函数,使用双向迭代器的reverse
reverse(nums.begin()+i+1,nums.end());

0 0
原创粉丝点击