LeetCode_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

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));
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值