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,23,2,1 → 1,2,31,1,5 → 1,5,1
题目意思:给你一串数,要找到下一个排列,比这个排列大,并且恰好比这个排列大,就是说对于原排列和新排列没法找到另一个排列插在这二者之间。比如1,2,3,值是123,那么下一个排列就是132,你没法找到一个居于123和132之间的排列。
public class Solution {
public void nextPermutation(int[] nums) {
if (nums == null || nums.length == 0) {
return ;
}
int i = nums.length-2;
while (i >= 0 && nums[i] >= nums[i+1]) {
i--;
}
if (i >= 0) {
int j = i + 1;
while (j < nums.length && nums[j] > nums[i]) {
j++;
}
j--;
swap(nums, i, j);
}
reverse(nums, i+1, nums.length-1);
}
private void reverse(int[] nums, int i, int j) {
// TODO Auto-generated method stub
while (i < j) {
swap(nums, i,j);
i++;
j--;
}
}
private void swap(int[] nums, int i, int j) {
// TODO Auto-generated method stub
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
本文介绍了一个算法问题——寻找给定数字序列的下一个排列。通过实例解释了问题的目标,并提供了一个Java解决方案,包括寻找下一个更大排列的方法及如何进行原地替换。
538

被折叠的 条评论
为什么被折叠?



