LeetCode刷题之Next Permutation

Problem

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
My Solution

class Solution {
    public static int[] nums;

    public void nextPermutation(int[] nums) {
        int index = findIndex(nums);

        if (index == 0) {
            reverse(nums, index);
            return ;
        }

        exchangeHead(nums, index);
        reverse(nums, index);
    }

    public int findIndex(int[] nums) {
        for (int i = nums.length - 1; i > 0; --i) {
            if (nums[i] > nums[i - 1]) {
                return i;
            }
        }
        return 0;
    }

    public void exchangeHead(int[] nums, int index) {
        int head = nums[index - 1];
        for (int i = nums.length - 1; i >= 0; --i) {
            if (head < nums[i]) {
                nums[index - 1] = nums[i];
                nums[i] = head;
                break;
            }
        }
    }

    public void reverse(int[] nums, int index) {
        int p = index;
        for (int i = nums.length - 1; i > p; --i,++p) {
            int temp = nums[i];
            nums[i] = nums[p];
            nums[p] = temp;
        }
    }
}  
Great Solution

public void nextPermutation(int[] A) {
    if(A == null || A.length <= 1) return;
    int i = A.length - 2;
    while(i >= 0 && A[i] >= A[i + 1]) i--; // Find 1st id i that breaks descending order
    if(i >= 0) {                           // If not entirely descending
        int j = A.length - 1;              // Start from the end
        while(A[j] <= A[i]) j--;           // Find rightmost first larger id j
        swap(A, i, j);                     // Switch i and j
    }
    reverse(A, i + 1, A.length - 1);       // Reverse the descending sequence
}

public void swap(int[] A, int i, int j) {
    int tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
}

public void reverse(int[] A, int i, int j) {
    while(i < j) swap(A, i++, j--);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,211评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,628评论 0 23
  • 还有一个星期,暑假就结束了,儿子的暑假作业却几乎没动,以往暑假快结束时,儿子会疯狂地补暑假作业。可是,...
    邱春兰阅读 1,877评论 1 1
  • 要理解以太坊 PrivateNetwork 先要理解以太坊的两种官方网络 目前以太坊官方提供了两种网络 生产环境网...
    yuyangray阅读 3,106评论 0 2
  • 那年。。。。
    留栀阅读 2,548评论 2 1

友情链接更多精彩内容