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

10/31

My solution:

three example cases:

  1. [1,2,3,4] => [1,2,4,3]
  2. [1,2,4,3] =>[1,3,2,4]
  3. [4,3,2,1] => [1,2,3,4]

Step 1: find the largest i s.t. A[i] < A[i+1] by scanning backwards

in case 1,  i = 2

in case 2, i = 1

in case 3, no such i, i.e. i = -1 < 0

After doing this, note that A[i+1~len-1] are in the descending order.

Step 2: if i < 0, then simply return A in ascending order (no need to sort, just reverse)

that is case 3, which is already the maximum

Step 3: if i >= 0, then sort A[i+1, len] (again no need to sort but simply reverse) and then swap i and j, where A[j] is the first element s.t. A[j] > A[i] and j > i


<pre name="code" class="java">public class Solution {
    public void nextPermutation(int[] A) {
        int len = A.length;
        // step 1: scan backwards to find i s.t. A[i] < A[i+1]
        int i = len-2;
        while(i >= 0){
            if(A[i] < A[i+1])       break;
            else i--; // err1: forget about this
        }
        
        if(i < 0){
            // A[i] >= A[i+1] for all i
            reverse(A,0, len-1);
            return;
        }
        
        // note that A[i] < A[i+1]
        reverse(A,i+1, len-1);
        // swap A[i] with A[j] with the first A[j] > A[i] s.t. j>i
        for(int j=i+1; j<len; j++){
            if(A[j] > A[i]){
                swap(A,i,j);
                break; // err2: forget to break
            }
        }
        
    }
    
    
    private void reverse(int[] A, int from, int to){
        int start = from, end  = to;
        while(start < end){
            swap(A, start, end);
            start++;
            end--;
        }
        
    }
    
    private void swap(int[] A, int i, int j){
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
    
    
}


 

Time complexity: O(n), find i,  reverse and swap

Space complexity is O(1)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值