Leetcode刷题记——31. Next Permutation(下一个排列)

本文介绍了LeetCode中31题的解题思路和Java实现。题目要求在原地实现数字排列的下一个更大排列,如果没有更大的排列,则将其排序为升序。文章详细解释了如何通过从后向前遍历来判断是否存在更大排列,并提供了相应的源码实现。

一、题目叙述:

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

二、解题思路:

题目的意思是:给定一个数字排列,让你输出下一个比这个数字排列大的数字排列,即最小的比给定数字大的数字排列。若没有,把数组从小到大排序。

1、首先,我们考虑给定一个数字排列,是否有比它更大的排列(即若排列为逆序就没有更大的排列了)?这是第一步,判断的方法是,从后往前遍历数组,判断后一位是否比前一位小,一旦遇到不是的,那么就必定存在比给定排列更大的排列(此时跳出循环,并记下此时循环变量flag,方便后面使用);否则,不存在更大的。

2、若不存在更大的,那把数组逆序一下即可。

3、若存在,说明要构造一个更大的排列了,在第一步我们记下的循环变量值flag,即是要进行改变的位置。此时循环检测flag后面的值,找到最小的比flag位置的值大的值的位置(好绕呦,结合代码看看喽),交换这两个值,然后把flag之后的值按升序排列即可。

ps:我要说,我的英语真是有够烂的,每次都看不懂题,所以单词还是要接着好好背!

三、源码:

import java.util.Arrays;

public class Solution
{
    public void nextPermutation(int[] nums) 
    {
    	
    	int n = nums.length;
    	int flag = n - 2;
    	boolean hasmore = false;
        for (int i = n - 1; i > 0; i--)//先检查给定数字是否有更大的组合
        	if (nums[i - 1] < nums[i])
        	{
        		hasmore = true;
        		flag = i - 1;
        		break;
        	}
        if (hasmore == false)//若没有,逆序数组,返回
        {
        	for (int i = 0; i < n/2; i++)
        	{
        		int temp = nums[i];
        		nums[i] = nums[n - i - 1];
        		nums[n - i -1] = temp;
        	}
        	return;	
        }
        else//若有,构造第一个比给定数字大的数
        {
        	int max = flag + 1;
        	for (int i = max; i < n; i++)
        		if (nums[i] > nums[flag] && nums[i] < nums[max])
        			max = i;
        	int temp = nums[flag];
        	nums[flag] = nums[max];
        	nums[max] = temp;
        	Arrays.sort(nums, flag + 1, n);
        	
        	return;
        }
        
    }
    public static void main(String[] args)
    {
    	int[] nums = {1,2,3};
    	Solution sol = new Solution();
    	sol.nextPermutation(nums);
    	for (int i = 0; i < nums.length; i++)
    	{
    		System.out.print(nums[i]);
    	}
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值