当前位置:网站首页>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());
}
};
边栏推荐
猜你喜欢
剑指 Offer 06.从头到尾打印链表
R language [import and export of dataset]
How to adjust bugs in general projects ----- take you through the whole process by hand
Talking about JVM (frequent interview)
Personal developed penetration testing tool Satania v1.2 update
Some common problems in the assessment of network engineers: WLAN, BGP, switch
Wazuh开源主机安全解决方案的简介与使用体验
In this indifferent world, light crying
API related to TCP connection
Reader writer model
随机推荐
Annotation and reflection
Introduction and experience of wazuh open source host security solution
Individual game 12
Sword finger offer 09 Implementing queues with two stacks
AtCoder Grand Contest 013 E - Placing Squares
kubeadm系列-02-kubelet的配置和启动
Smart construction site "hydropower energy consumption online monitoring system"
剑指 Offer 06.从头到尾打印链表
Educational Codeforces Round 107 (Rated for Div. 2) E. Colorings and Dominoes
【Jailhouse 文章】Performance measurements for hypervisors on embedded ARM processors
Daily question 1984 Minimum difference in student scores
Drawing dynamic 3D circle with pure C language
Daily question 1688 Number of matches in the competition
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
注解与反射
Kubedm series-00-overview
剑指 Offer 09. 用两个栈实现队列
API related to TCP connection
剑指 Offer 58 - II. 左旋转字符串
lxml. etree. XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8