31. Next Permutation

题目描述:

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 and use only constant 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

代码:

class Solution {
public:
    void sort(vector<int>& nums, int index){
        for(int i = index + 2; i < nums.size(); i++){
            for(int j = index + 1; j < i; j++){
                if(nums[i] < nums[j]){
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                }
            }
        }
    }
    void nextPermutation(vector<int>& nums) {
        int index = -1;
        for(int i = nums.size() - 2; i >= 0; i--){
            bool flag = false;
            for(int j = nums.size() - 1; j > i; j--){
                if(nums[i] < nums[j]){
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                    index = i;
                    flag = true;
                    break;
                }
            }
            if(flag) break;
        }
        sort(nums, index);
    }
};

 31题,Medium,三次AC,不要问我为什么没有按顺序写题,因为我也不知道哈哈,反正基本顺序差不多,看哪个顺眼做哪个。今天又是脑壳疼的一天。上午看了一上午论文,论文的一个算法看了好几天了看不懂,难受,什么时候能彻彻底底愉愉快快开开心心无忧无虑地敲代码啊。I like watching my fingers dancing on the keybord。哈哈哈,很装逼有木有。

题目要求,已知一个数组的排列,重新排列该数组为下一个排列。我的思路:

从数组最右端开始遍历,找该数右边从右数第一个大于它的数,进行交换。(MD好像有点拗口,GRD论文更拗口,还是英文的)。如果找到的话,记录一下该数的位置,index。最后将数组的index到结束的数字按照从小到大的顺序排列。sort函数是简单的插入排序(快排写一次忘一次也是难受的不行T.T)。简而言之就是你要想这个数字稍微大一点,那肯定是优先从个位数开始让他变大,否则它就不是大“一点”了。而且由于数组所有元素是不变的,也就是只能交换数字。那肯定是让该数字和它右边的比他大的数字的最小值进行交换,就行了。拗口拗口,不管了,意会吧。债见,滚去看论文了T.T

静心尽力!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值