31. Next Permutation

来源:互联网 发布:sql 唯一 distinct 编辑:程序博客网 时间:2024/06/06 02:34

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



思路:

(1)brute force,复杂度O(n^2),

(2)O(N):从右往左先找到第一个左边(记为i)比右边小的point,然后继续从最右边开始找到第一个比i大的point(记为j),i和j交换后,对从i+1位置开始到最右边的数进行排序(因为已经可以明确后面的这些是排好序的,所以直接swap就好了)

public class Solution {    public void nextPermutation(int[] nums) {        if(nums.length < 2)return ;                int i = nums.length - 1;                // find the key exchange point i        while(i > 0 && nums[i] <= nums[i-1])i--;        i--;                // biggest        if(i == -1){        reverse(nums, 0, nums.length-1);        return;        }                // from right to left, find the swap point j with i        int j = nums.length - 1;        while(nums[j] <= nums[i])j--;        swap(nums, i, j);        reverse(nums, i+1, nums.length-1);    }private void swap(int[] nums, int i, int j) {int tmp = nums[i];nums[i] = nums[j];nums[j] = tmp;}private void reverse(int[] nums, int i, int j) {while(i < j) {swap(nums, i, j);i++;j--;}}}



Brute Force:

import java.util.Arrays;public class Solution {    public void nextPermutation(int[] nums) {        for(int i=nums.length-2; i>=0; i--) {        int minBigger = Integer.MAX_VALUE, idx = -1;        for(int j=i+1; j<nums.length; j++) {        if(nums[j] > nums[i]) {        if(nums[j] < minBigger) {        minBigger = nums[j];        idx = j;        }        }        }                if(minBigger != Integer.MAX_VALUE) {        int temp = nums[idx];    nums[idx] = nums[i];    nums[i] = temp;    //System.out.println(j+1 + " " + i+1);    Arrays.sort(nums, i+1, nums.length);    return ;        }        }        //if(f)        Arrays.sort(nums);    }}



0 0
原创粉丝点击