Leetcode 556.下一个更大元素III
2024-09-29 04:39:51
下一个更大元素III
给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。
示例 1:
输入: 12
输出: 21
示例 2:
输入: 21
输出: -1
C++: using next permutation
int nextGreaterElement(int n) { auto digits = to_string(n); next_permutation(begin(digits), end(digits)); auto res = stoll(digits); return (res > INT_MAX || res <= n) ? -1 : res; } |
Java
import java.util.Arrays; public class Solution {
public int nextGreaterElement(int n) {
char[] number = (n + "").toCharArray(); int i, j;
// I) Start from the right most digit and
// find the first digit that is
// smaller than the digit next to it.
for (i = number.length-1; i > 0; i--)
if (number[i-1] < number[i])
break; // If no such digit is found, its the edge case 1.
if (i == 0)
return -1; // II) Find the smallest digit on right side of (i-1)'th
// digit that is greater than number[i-1]
int x = number[i-1], smallest = i;
for (j = i+1; j < number.length; j++)
if (number[j] > x && number[j] <= number[smallest])
smallest = j; // III) Swap the above found smallest digit with
// number[i-1]
char temp = number[i-1];
number[i-1] = number[smallest];
number[smallest] = temp; // IV) Sort the digits after (i-1) in ascending order
Arrays.sort(number, i, number.length); long val = Long.parseLong(new String(number));
return (val <= Integer.MAX_VALUE) ? (int) val : -1;
}
}
最新文章
- Laplacian matrix 从拉普拉斯矩阵到谱聚类
- git 使用入门篇
- 关闭“JDK自动更新”提示
- [shell基础]——整数比较;字符串比较;文件测试;逻辑测试符
- dojo.declare
- MYSQL 提取时间中的信息的 4 方法
- OAuth2.0认证过程
- 每篇半小时1天入门MongoDB——2.MongoDB环境变量配置和Shell操作
- GitHub中开启二次验证Two-factor authentication,如何在命令行下更新和上传代码
- Spring Boot 2.x(四):整合Mybatis的四种方式
- debian安装mongoDB
- navicat for mysql 12中文破解版(安装+破解)--亲测可用
- zyb的面试(广工14届比赛)
- ElasticSearch——日志工具
- PAT-1045. Favorite Color Stripe (30)-LIS
- Nginx配置——区分PC或手机访问不同域名以及http跳转https
- servlet转发与重定向区别
- 什么是 metadata (元数据)
- Solution for sending Whatsapp via sqlite ";INSERT INTO";
- 微服务实战(三):以MySQL为例,从原理上理解那些所谓的数据库军规
热门文章
- cms-后台eazyui搭建
- POJ1061 青蛙的约会 __一维世界的爱情
- Coursera 算法二 week 3 Baseball Elimination
- linux 命令——17 whereis(转)
- VS打包方法(安装和部署简介)——内含大量图片,密症慎入!
- hbase查询基于标准sql规范中间件Phoenix
- 【CF1000C】Covered Points Count(离散化+差分)
- 2018.5.22 Oracle安装配置在虚拟机中外部电脑连接服务
- python_77_json与pickle序列化3
- 抽屉head部分,hover应用,鼠标放上变色