Next Permutation_Leetcode_#31

来源:互联网 发布:python是什么语言 编辑:程序博客网 时间:2024/06/03 22:04

1.题目
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

2 解法

public class Solution {    public void nextPermutation(int[] nums) {        int size = nums.length;        if(size <= 1){            return;        }        int i = size - 1;        for(; i >= 1; i--){            if(nums[i] > nums[i-1]){                break;            }        }        if(i != 0){            swap(nums, i - 1);        }        reverse(nums, i);    }    // swap from the end, find the first element that is less than nums[i], sawp it with nums[i] and return;    public void swap(int[] nums, int i){        int j = nums.length - 1;        for(; j > 0; j--){            if(nums[j] > nums[i]){                int temp = nums[i];                nums[i] = nums[j];                nums[j] = temp;                return;            }                    }    }    public void reverse(int[] nums, int i){        int right = nums.length - 1;        int left = i;        while(left < right){            int temp = nums[left];            nums[left] = nums[right];            nums[right] = temp;            ++left;            --right;        }    }}
0 0
原创粉丝点击