leetcode 88: Next Permutation

本文介绍了一种名为NextPermutation的算法实现,该算法能够就地重排数组元素,形成字典序上的下一个更大排列。如果无法形成更大的排列,则将数组重排为最小可能的顺序(即升序)。文章提供了完整的Java代码示例,并通过几个实例演示了其工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1

public class Solution {
    public void nextPermutation(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int sz=num.length;
        if(sz<=1) return;
        
        int i=sz-1;
        while(i>0) {
            if(num[i-1]<num[i]) {
                break;
            }
            i--;
        }
        quickSort(num,i,sz-1);
        if(i==0) return;
        int j=i-1;
        while(num[j]>=num[i])i++;
        swap(num,j,i);
        
    }
    
    private void swap(int[] num, int x, int y) {
        num[x] = num[x]^num[y];
        num[y] = num[x]^num[y];
        num[x] = num[x]^num[y];
    }
    
    private void quickSort(int[] num, int x, int y) {
        if(x>=y) return;
        int q = partition(num,x,y);
        quickSort(num,x,q-1);
        quickSort(num,q+1,y);
    }
    
    private int partition(int[] num, int p, int r) {
        int pivot = num[r];
        
        int i=p-1;
   
        for(int j=p ; j<r-1; j++) {
            if(num[j]<=pivot) {
                i++;
                swap(num, i, j);
            }
        }
        swap(num, i+1, r);
        return i+1;
    }
}





转载于:https://www.cnblogs.com/xishibean/archive/2013/02/23/2951299.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值