当前位置:网站首页>leetcode-31:下一个排列
leetcode-31:下一个排列
2022-07-05 05:46:00 【菊头蝙蝠】
题目
题目连接
整数数组的一个 排列 就是将其所有成员以序列或线性顺序排列。
- 例如,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 的下一个排列。
必须 原地 修改,只允许使用额外常数空间。
示例 1:
输入:nums = [1,2,3]
输出:[1,3,2]
示例 2:
输入:nums = [3,2,1]
输出:[1,2,3]
示例 3:
输入:nums = [1,1,5]
输出:[1,5,1]
解题
方法一:
- 以12385764为例子,由于要查找下一个更大的,因此要倒序遍历。
- 倒序遍历,找到第一个递增的相邻元素57 (因此后面的元素一定是递减的,764)
- 然而并不能直接让5和7进行交换,而是让5和6交换。因此倒序遍历到找第一个比5大的元素,是6
- 交换完后变成了12386754,然而这并不是想要的下一个更大的元素(而是下面好几个元素)。因此对后面部分进行排序 12386 754---->12386 457
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n=nums.size();
int i=n-2,j=n-1;
while(i>=0&&nums[i]>=nums[j]){
i--;
j--;
}
int k=n-1;
if(i>=0){
while(nums[i]>=nums[k]) k--;
swap(nums[i],nums[k]);
}
sort(nums.begin()+i+1,nums.end());
}
};
边栏推荐
- EOJ 2021.10 E. XOR tree
- SSH password free login settings and use scripts to SSH login and execute instructions
- Using HashMap to realize simple cache
- 884. Uncommon words in two sentences
- 2022 极术通讯-Arm 虚拟硬件加速物联网软件开发
- R language [import and export of dataset]
- R语言【数据集的导入导出】
- Haut OJ 2021 freshmen week II reflection summary
- Graduation project of game mall
- 1.15 - 输入输出系统
猜你喜欢

Dichotomy, discretization, etc

Time of process
![[jailhouse article] jailhouse hypervisor](/img/f4/4809b236067d3007fa5835bbfe5f48.png)
[jailhouse article] jailhouse hypervisor

Sword finger offer 06 Print linked list from beginning to end

Sword finger offer 04 Search in two-dimensional array

Scope of inline symbol

【实战技能】如何做好技术培训?

In this indifferent world, light crying

Sword finger offer 58 - ii Rotate string left

Sword finger offer 05 Replace spaces
随机推荐
1.13 - RISC/CISC
26、 File system API (device sharing between applications; directory and file API)
7. Processing the input of multidimensional features
Alu logic operation unit
Codeforces round 712 (Div. 2) d. 3-coloring (construction)
Smart construction site "hydropower energy consumption online monitoring system"
Common optimization methods
API related to TCP connection
Zheng Qing 21 ACM is fun. (3) part of the problem solution and summary
Introduction and experience of wazuh open source host security solution
Implement an iterative stack
Scope of inline symbol
CCPC Weihai 2021m eight hundred and ten thousand nine hundred and seventy-five
Sword finger offer 53 - I. find the number I in the sorted array
Daily question 2006 Number of pairs whose absolute value of difference is k
Acwing 4300. Two operations
LeetCode 0107.二叉树的层序遍历II - 另一种方法
Introduction to convolutional neural network
[practical skills] how to do a good job in technical training?
YOLOv5-Shufflenetv2