leetcode 88: Next Permutation

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;
    }
}





posted @ 2013-02-23 17:52  西施豆腐渣  阅读(97)  评论(0编辑  收藏  举报