当前位置:网站首页>下一个排列
下一个排列
2022-08-02 07:49:00 【ZEKEGU1997】
问题描述
整数数组的一个 排列 就是将其所有成员以序列或线性顺序排列。
例如,arr = [1,2,3] ,以下这些都可以视作 arr 的排列:[1,2,3]、[1,3,2]、[3,1,2]、[2,3,1] 。
整数数组的 下一个排列 是指其整数的下一个字典序更大的排列。更正式地,如果数组的所有排列根据其字典顺序从小到大排列在一个容器中,那么数组的 下一个排列 就是在这个有序容器中排在它后面的那个排列。如果不存在下一个更大的排列,那么这个数组必须重排为字典序最小的排列(即,其元素按升序排列)。
例如,arr = [1,2,3] 的下一个排列是 [1,3,2] 。
类似地,arr = [2,3,1] 的下一个排列是 [3,1,2] 。
而 arr = [3,2,1] 的下一个排列是 [1,2,3] ,因为 [3,2,1] 不存在一个字典序更大的排列。
给你一个整数数组 nums ,找出 nums 的下一个排列。
解法

步骤:
- 从最后一个开始向前寻找到第一个降序的元素i,若未找到说明已经是最大的排列
- 从最后一个开始向前寻找到第一个比i大的元素j、
- 交换元素ij
- 将i+1至末尾之间的元素逆置
public class Solution {
public void NextPermutation(int[] nums) {
if(nums.Length==1)
return;
int i=nums.Length-2;
while(i>=0&&nums[i]>=nums[i+1])
i--;
if(i<0)
{
Array.Sort(nums);
return;
}
int j=nums.Length-1;
while(j>i&&nums[j]<=nums[i])
j--;
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
int a=i+1,b=nums.Length-1;
while(a<b)
{
t=nums[a];
nums[a]=nums[b];
nums[b]=t;
a++;b--;
}
return;
}
}边栏推荐
猜你喜欢
![[ansible] playbook explains the execution steps in combination with the project](/img/fe/82b8562075fef33490d5aae7e809f5.png)
[ansible] playbook explains the execution steps in combination with the project

Biotin - LC - Hydrazide | CAS: 109276-34-8 | Biotin - LC - Hydrazide

MySQL事务隔离级别详解

Button to control the running water light (timer)

Visual Analysis of DeadLock

原型模式

Inverter insulation detection detection function and software implementation

Buried development process

HCIP第一天

BGP通过MPLS解决路由黑洞
随机推荐
@PostConstruct注解详解
Data Middle Office: Started in Ali, Prosperous in DaaS
postgres groupby merge strings
PanGu-Coder: A function-level code generation model
59: Chapter 5: Develop admin management services: 12: MongoDB usage scenarios; (non-core data, non-core data with a relatively large amount of data, small private files such as face photos;)
传递泛型给JSX元素
Comprehensive experiment of MPLS and BGP
MySQL - locking mechanism
@RequestParam使用
PanGu-Coder:函数级的代码生成模型
【Network】IP, subnet mask
mysql启动报错The server quit without updating PID file几种解决办法
Elasticserch 自定义字段,用户会频繁的创建和删除字段,怎么设计mapping?
7.联合索引(最左前缀原则)
【Unity3D】初学加密技巧(反破解)
MySQL - Detailed Explanation of Database Transactions
Stop mental exhaustion Daily sharing
CASA模型、CENTURY模型应用与案例分析
小说里的编程 【连载之二十四】元宇宙里月亮弯弯
知识点滴 - 为什么一般不用铜锅做菜