下一个更大元素III

给定一个32位正整数 n,你需要找到最小的32位整数,其与 中存在的位数完全相同,并且其值大于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;
}
}

最新文章

  1. Laplacian matrix 从拉普拉斯矩阵到谱聚类
  2. git 使用入门篇
  3. 关闭“JDK自动更新”提示
  4. [shell基础]——整数比较;字符串比较;文件测试;逻辑测试符
  5. dojo.declare
  6. MYSQL 提取时间中的信息的 4 方法
  7. OAuth2.0认证过程
  8. 每篇半小时1天入门MongoDB——2.MongoDB环境变量配置和Shell操作
  9. GitHub中开启二次验证Two-factor authentication,如何在命令行下更新和上传代码
  10. Spring Boot 2.x(四):整合Mybatis的四种方式
  11. debian安装mongoDB
  12. navicat for mysql 12中文破解版(安装+破解)--亲测可用
  13. zyb的面试(广工14届比赛)
  14. ElasticSearch——日志工具
  15. PAT-1045. Favorite Color Stripe (30)-LIS
  16. Nginx配置——区分PC或手机访问不同域名以及http跳转https
  17. servlet转发与重定向区别
  18. 什么是 metadata (元数据)
  19. Solution for sending Whatsapp via sqlite &quot;INSERT INTO&quot;
  20. 微服务实战(三):以MySQL为例,从原理上理解那些所谓的数据库军规

热门文章

  1. cms-后台eazyui搭建
  2. POJ1061 青蛙的约会 __一维世界的爱情
  3. Coursera 算法二 week 3 Baseball Elimination
  4. linux 命令——17 whereis(转)
  5. VS打包方法(安装和部署简介)——内含大量图片,密症慎入!
  6. hbase查询基于标准sql规范中间件Phoenix
  7. 【CF1000C】Covered Points Count(离散化+差分)
  8. 2018.5.22 Oracle安装配置在虚拟机中外部电脑连接服务
  9. python_77_json与pickle序列化3
  10. 抽屉head部分,hover应用,鼠标放上变色