您的位置:首页 > 其它

LeetCode_31---Next Permutation

2015-06-15 15:40 537 查看
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


Hide Tags
 Array

翻译:
https://leetcode.com/problems/next-permutation/
Code:

/**
*
*/
package From21;

import java.util.Arrays;

/**
* @author MohnSnow
* @time 2015年6月15日 下午3:39:47
* @reference http://blog.csdn.net/cinderella_niu/article/details/42525241 * @translate 思路:所谓一个排列的下一个排列的意思就是,在这一个排列和下一个排列之间没有其他的排列。
* 这就要求我们这一个排列和下一个排列拥有尽可能长的共同前缀,也即变化限制在尽可能短的后缀上。
* @nextTrans 1.从后往前,找到第一个 A[i-1] < A[i]的。也就是第一个排列中的 6那个位置,可以看到A[i]到A[n-1]这些都是单调递减序列。9,8,7,2递减
* 2.从 A[n-1]到A[i]中找到一个比A[i-1]大的值(也就是说在A[n-1]到A[i]的值中找到比A[i-1]大的集合中的最小的一个值)。从末尾找到第一个大于i 的元素,记为 j。即7。
* 3.交换 这两个值,并且把A[n-1]到A[i]排序,从小到大。由于j是第一个大于i的元素,则交换后,之后仍然满足递减排列,直接reverse得到升序排列。8 6 4 3 2按照递增重新排列。
* 4. 如果某个排列没有比他大的下一个排列(即该排列是递增有序的),翻转整个排列,得到最小的排列。
*/
public class LeetCode31 {

/**
* @param argsmengdx
* -fnst
*/
//344msA
public static void nextPermutation(int[] nums) {
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] <= nums[i - 1]) {
if (i == 1) {
Arrays.sort(nums);
System.out.println("i111:" + i);
return;
} else {
continue;
}
} else {
break;
}
}
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
int j = i;
while (j < nums.length) {
if (nums[i - 1] < nums[j]) {
j++;
} else {
break;
}
}
int temp = nums[i - 1];
nums[i - 1] = nums[j - 1];
nums[j - 1] = temp;
System.out.println("i:" + i);
Arrays.sort(nums, i, nums.length);
break;
} else {
continue;
}
}
}

public static void main(String[] args) {
int[] nums = { 5, 1, 1 };
nextPermutation(nums);
System.out.println("算法一:" + Arrays.toString(nums));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 LeetCode