您的位置:首页 > 其它

leetcode (31) Next Permutation

2016-06-01 20:09 381 查看
题目链接:https://leetcode.com/problems/next-permutation/

题目: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


题目解析:题目的意思,找一个排列的下一个排列,简单来说,就是比原排列大,并且最接近原排列的就是下一个排列。但是如果没有下一个排列的情况,那么就把数组旋转过来。

解题思路:

(1)从后向前,找到第一个i,满足nums[i] < nums[i+1];若找不到满足的i,直接翻转数组即是所求。

(2)从后向前,numsSize-1到i之间,找到第一个比nums[i]大的数,索引位j

(3)交换nums[i]和nums[j]

(4)将nums[i]之后的数进行一个排序

(5)最后所得的数就是下一个排列。

代码实现:

#include <stdio.h>

void quickSort(int *nums, int start, int end) {

    if (start >= end) return;

    int flag = nums[start];

    int left = start;

    int right = end;

    while (left < right) {

        while(left < right && nums[right] >= flag) {

            right--;

        }

        if(left < right) {

            nums[left] = nums[right];

        }

        while(left < right && nums[left] <= flag) {

            left++;

        }

        if(left < right) {

            nums[right] = nums[left];

        }

    }

    nums[left] = flag;

    quickSort(nums, start, left-1);

    quickSort(nums, left+1, end);

}

void nextPermutation(int* nums, int numsSize) {

    int position = -1;

    for (int i = numsSize-1; i > 0; i--) {

        if (nums[i] > nums[i-1]) {

            position = i-1;

            break;

        }

    }

    if (position == -1) {

        for (int i = 0; i < numsSize/2; i++) {

            int tmp = nums[i];

            nums[i] = nums[numsSize-i-1];

            nums[numsSize-i-1] = tmp;

        }

        return;

    }

    for (int i = numsSize-1; i > 0; i--) {

        if (nums[i] > nums[position]) {

            int tmp = nums[position];

            nums[position] = nums[i];

            nums[i] = tmp;

            break;

        }

    }

    quickSort(nums, position+1, numsSize-1);

}

int main() {

    int nums[5] = {1,2,5,4,3};

    //quickSort(nums, 0, 4);

    nextPermutation(nums, 5);

    for(int i = 0; i < 5; i++) {

        printf("%d\n", nums[i]);

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息