《leetCode》: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, 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,31,3,2
3,2,11,2,3
1,1,51,5,1

题目大意:找出大于当前排列的下一个排列。如果当前排列是最大的排列,则返回最小的排列。

思路

思路:
第一步:从后开始遍历,找到第一个相邻两个元素升序的位置pos.
第二步:如果没有找到pos,则说明是最大的一个排列,将其反序即可。如果找到了pos,
则从后开始遍历,找到第一个大于nums[pos]值的位置k,然后交换nums[pos]与nums[k] 的位置
第三步:将pos之后的所有元素进行一个排序(升序)即可

实现代码如下:



int cmp(const void * a,const void *b){
    return (*((int *)a))-(*((int *)b));
}
void nextPermutation(int* nums, int numsSize) {
    if(nums==NULL||numsSize<2){
        return;
    }
    int pos=-1; 
    //第一步:从后开始遍历,找到第一个相邻两个元素升序的位置pos. 
    for(int i=numsSize-1;i>0;i--){
        if(nums[i]>nums[i-1]){
            pos=i-1;
            break;
        }
    }
    if(pos==-1){//说明此数时最大的一个排列,则将其排序即可
        qsort(nums,numsSize,sizeof(nums[0]),cmp); 
        return;     
    } 
    //此种情况说明,找到了升序的位置
    //第二步:从后开始遍历,找到,第一个大于nums[pos]的位置k,并将其交换
    for(int i=numsSize-1;i>0;i--){
        if(nums[i]>nums[pos]){
            int temp=nums[i];
            nums[i]=nums[pos];
            nums[pos]=temp;
            break;
        }
    }
    //第三步:将nums数组中从下标pos以后的数进行排序
    qsort(nums+pos+1,numsSize-pos-1,sizeof(nums[0]),cmp) ;


}

最后AC结果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值