当前位置:网站首页>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());
}
};
边栏推荐
猜你喜欢

Implement a fixed capacity stack

网络工程师考核的一些常见的问题:WLAN、BGP、交换机

LeetCode 0107.二叉树的层序遍历II - 另一种方法
![[practical skills] technical management of managers with non-technical background](/img/4d/1081c71df6ee2087359111baf7498a.png)
[practical skills] technical management of managers with non-technical background

Graduation project of game mall

Hang wait lock vs spin lock (where both are used)

剑指 Offer 05. 替换空格

剑指 Offer 04. 二维数组中的查找
![[jailhouse article] performance measurements for hypervisors on embedded ARM processors](/img/c0/4843f887f77b80e3b2329e12d28987.png)
[jailhouse article] performance measurements for hypervisors on embedded ARM processors

On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
随机推荐
Sword finger offer 06 Print linked list from beginning to end
Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module
【实战技能】如何做好技术培训?
One question per day 1765 The highest point in the map
How to adjust bugs in general projects ----- take you through the whole process by hand
Configuration and startup of kubedm series-02-kubelet
Daily question 1688 Number of matches in the competition
In this indifferent world, light crying
[cloud native] record of feign custom configuration of microservices
浅谈JVM(面试常考)
Palindrome (csp-s-2021-palin) solution
CF1634E Fair Share
R language [import and export of dataset]
Zheng Qing 21 ACM is fun. (3) part of the problem solution and summary
【Jailhouse 文章】Jailhouse Hypervisor
Light a light with stm32
2022 pole technology communication arm virtual hardware accelerates the development of Internet of things software
Daily question 1342 Number of operations to change the number to 0
[article de jailhouse] jailhouse hypervisor
LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树