您的位置:首页 > 其它

LeetCode:Next Permutation

2016-07-01 12:44 405 查看


Next Permutation

Total Accepted: 70533 Total
Submissions: 261357 Difficulty: Medium

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


Subscribe to see which companies asked this question

Hide Tags
Array

Hide Similar Problems
(M) Permutations (M)
Permutations II (M) Permutation Sequence (M)
Palindrome Permutation II

思路:

下一个排列数,定义:比当前数大的最小数。

1.从左往右找到第一个“顺序”,即nums[i-1] <nums[i],因此nums[i,n-1]都是“逆序”;

2.从定义可知,我们要从[i,n-1]中找一个最小的数与nums[i-1]交往,然后将nums[i,n-1]“顺序”排序即可。

如:nums = [6,2,5,4,3,1], n = 6;

由1)找到i = 2,nums[2,5] = [5,4,3,1]是“逆序”;

由2)交换后得 nums=[6,3,5,4,2,1],再将[i, n-1]顺序,得解[6,3,1,2,4,5];

由于[i, n-1]已是逆序,直接逆序就变成“顺序”,时间O(n),即总时间O(n);

java code:

public class Solution {
public void nextPermutation(int[] nums) {

int n = nums.length;
int i = n-1;
// 从左到右,找到第一个“顺序”位置
while(i > 0) {
if(nums[i-1] < nums[i]) break;
i--;
}

if(i==0) {
reverse(nums, 0, n-1);
return;
}

// 找到第一个大于i位置值的下标j,并与i位置值交换
int j = n-1;
int val = nums[i-1];
while(i < j && val >= nums[j]) j--;
swap(nums, i-1, j);
// 逆序[i,n-1]部分
reverse(nums, i, n-1);

}

// 自定义函数:逆序
void reverse(int[] nums, int lo, int hi) {
while(lo < hi) {
swap(nums, lo, hi);
lo++;hi--;
}
}
// 交换
void swap(int[] nums, int lo, int hi) {
nums[lo] ^= nums[hi];
nums[hi] ^= nums[lo];
nums[lo] ^= nums[hi];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: