当前位置:网站首页>【Hot100】31. 下一个排列
【Hot100】31. 下一个排列
2022-07-04 16:03:00 【王六六的IT日常】
中等题
整数数组的 下一个排列 是指其整数的下一个字典序更大的排列。
解题思路:
- 找到第一个比后面小的元素
- 与后面比它大的最小值交换
- 交换后使他后面的数字升序排列, reverse即可, 因为 1. 的特性,后面是降序排列的
class Solution {
public void nextPermutation(int[] nums) {
int pre = nums.length - 2;
while (pre >= 0 && nums[pre] >= nums[pre + 1]) pre--;
if (pre == -1) reverse(nums, 0, nums.length - 1); // 边界值处理
else {
int post = pre + 1;
while (post < nums.length && nums[post] > nums[pre]) post++;
post--;
int t = nums[pre];
nums[pre] = nums[post];
nums[post] = t;
reverse(nums, pre + 1, nums.length - 1);
}
}
void reverse(int[] nums, int l, int r) {
while (l < r) {
int t = nums[l];
nums[l++] = nums[r];
nums[r--] = t;
}
}
}
边栏推荐
猜你喜欢
解读数据安全治理能力评估框架2.0,第四批DSG评估征集中
超标量处理器设计 姚永斌 第5章 指令集体系 摘录
With an annual income of more than 8 million, he has five full-time jobs. He still has time to play games
7 RSA密码体制
VB cannot access database stocks
【HCIA持续更新】广域网技术
[test development] software testing - Basics
就在今天丨汇丰4位专家齐聚,共讨银行核心系统改造、迁移、重构难题
Internet addiction changes brain structure: language function is affected, making people unable to speak neatly
Ks007 realizes personal blog system based on JSP
随机推荐
leetcode刷题目录总结
Dynamic programming stock problem comparison
中银证券网上开户安全吗?
新享科技发布小程序UniPro小优 满足客户移动办公场景
Which domestic cloud management platform manufacturer is good in 2022? Why?
Is BigDecimal safe to calculate the amount? Look at these five pits~~
Go micro tutorial - Chapter 2 go micro V3 using gin and etcd
国产数据库TiDB初体验:简单易用,快速上手
Vscode modification indentation failed, indent four spaces as soon as it is saved
动态规划股票问题对比
CocosCreator事件派发使用
shell脚本的替换功能实现
Detectron2 installation method
VB cannot access database stocks
Redis 的内存淘汰策略和过期删除策略的区别
7 RSA Cryptosystem
Display opencv drawn pictures on MFC picture control control
Kunming Third Ring Road Closure project will pass through these places. Is there one near your home?
CocosCreator事件派發使用
安信证券属于什么档次 开户安全吗