Leetcode 556.下一个更大元素III

下一个更大元素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

 1 import java.util.Arrays;
 2 
 3 public class Solution {
 4     public int nextGreaterElement(int n) {
 5         char[] number = (n + "").toCharArray();
 6 
 7         int i, j;
 8         // I) Start from the right most digit and
 9         // find the first digit that is
10         // smaller than the digit next to it.
11         for (i = number.length-1; i > 0; i--)
12             if (number[i-1] < number[i])
13                 break;
14 
15         // If no such digit is found, its the edge case 1.
16         if (i == 0)
17             return -1;
18 
19         // II) Find the smallest digit on right side of (i-1)'th
20         // digit that is greater than number[i-1]
21         int x = number[i-1], smallest = i;
22         for (j = i+1; j < number.length; j++)
23             if (number[j] > x && number[j] <= number[smallest])
24                 smallest = j;
25 
26         // III) Swap the above found smallest digit with
27         // number[i-1]
28         char temp = number[i-1];
29         number[i-1] = number[smallest];
30         number[smallest] = temp;
31 
32         // IV) Sort the digits after (i-1) in ascending order
33         Arrays.sort(number, i, number.length);
34 
35         long val = Long.parseLong(new String(number));
36         return (val <= Integer.MAX_VALUE) ? (int) val : -1;
37     }
38 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值