LeetCode----- 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, 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 NextPermutation {

	public static void main(String[] args) {
		int[] num = new int[]{3,2,1};
		nextPermutation(num);
		for (int i = 0; i < num.length; i++) {
			if(i == num.length-1) {
				System.out.println(num[i]);
			}else {
				System.out.print(num[i]+",");
			}
		}
	}
	
    public static void nextPermutation(int[] nums) {
    	int front = -1;
    	for (int i = nums.length-2; i>=0; i--) {
			if(nums[i] < nums[i+1]) {
				front = i;
				break;
			}
		}
    	if(front>=0) {
    		for (int i=nums.length-1; i>front;i--) {
				if(nums[i] > nums[front]) {
					swap(nums, i, front);
					break;
				}
			}
    	}
    	sort(nums, front+1);
    }
    
    public static void swap(int[] num,int x,int y) {
    	int temp = num[x];
    	num[x] = num[y];
    	num[y] = temp;
    }
    
    public static void sort(int[] num,int index) {
    	int end = num.length-1;
    	int start = index;
    	while(start < end) {
    		swap(num, start, end);
    		start++;
    		end--;
    	}
    }

}



















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章