码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Next Permutation

时间:2015-04-02 16:32:47      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:leetcode   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,2,3,4,5->1,2,3,5,4->1,2,4,3,5->1,2,4,5,3-> ... -> 5,4,3,2,1

现在用int[] a = {1,3,4,5,2}做实例

这里的解决步骤是:

1.从后往前找到一个降序排列,将较小的下标设为i,如在a中为a[2]=4,i为2。

2.从后往前找一个比a[i]大的数a[j],这里为a[3]=5,即j=3.

3.交换下标为i和下标为j的数位置,这里也就是交换a[2]和a[3],得到:a={1,3,5,4,2}

4.对i之后的数字进行排序,这里i=2,也就是对a[2]之后的数字进行排序,得到:a={1,3,5,2,4}

原因暂时没想到

code:

package alivebao;

import java.util.Arrays;

/**
 * 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
 * 
 * @author Administrator
 * 
 */
public class Solution {
	public static void nextPermutation(int[] num) {
		if (num.length <= 1)
			return;
		for (int i = num.length - 2; i >= 0; i--) {
			if (num[i] < num[i + 1]) {
				int j;
				for (j = num.length - 1; j >= i; j--)
					if (num[i] < num[j])
						break;
				// swap the two numbers.
				int temp = num[i];
				num[i] = num[j];
				num[j] = temp;
				// sort the rest of arrays after the swap point.
				Arrays.sort(num, i + 1, num.length);

				for (int z : num)
					System.out.println(z);

				return;
			}
		}
		// reverse the arrays.
		for (int i = 0; i < num.length / 2; i++) {
			int tmp = num[i];
			num[i] = num[num.length - i - 1];
			num[num.length - i - 1] = tmp;
		}
		for (int i : num)
			System.out.println(i);
		return;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] num = { 1, 4, 3, 5, 2 };
		nextPermutation(num);
	}
}


LeetCode-Next Permutation

标签:leetcode   next permutation   

原文地址:http://blog.csdn.net/miaoyunzexiaobao/article/details/44832559

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!