Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer nand is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

  1. Input: 12
  2. Output: 21

Example 2:

  1. Input: 21
  2. Output: -1

给一个32字节的正整数,找出由同样数位组成比给定数大的数字中最小的,其实就是对各个数位重新排序,求出刚好比给定数字大的一种排序,如果不存在就返回-1。

Java:

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

Java:

  1. class Solution {
  2. public int nextGreaterElement(int n) {
  3. // The same as : leetcode 31 Next Permutation, O(n)
  4. char[] number = (n + "").toCharArray();
  5. int i = -1;
  6. //1. find backwards
  7. for(i = number.length - 1; i > 0; i--)
  8. if(number[i - 1] < number[i])
  9. break;
  10. if(i == 0)
  11. return -1;
  12. //2. first, second
  13. int first = i - 1, second = i;
  14. //3. find the next greater than first, backward
  15. for(i = number.length - 1; i > first; i--) {
  16. if(number[i] > number[first]) {
  17. char temp = number[i];
  18. number[i] = number[first];
  19. number[first] = temp;
  20. break;
  21. }
  22. }
  23. //4. reverse after second
  24. reverse(number, second);
  25.  
  26. //5. Transform back
  27. long val = Long.parseLong(new String(number));
  28. return (val <= Integer.MAX_VALUE) ? (int) val : -1;
  29.  
  30. }
  31.  
  32. private void reverse(char[] a,int i)//reverse the number after the number we have found
  33. {
  34. int first = i;
  35. int last = a.length-1;
  36. while(first<last)
  37. {
  38. char t = a[first];
  39. a[first] = a[last];
  40. a[last] = t;
  41. first ++;
  42. last --;
  43. }
  44. }
  45. }  

Python:

  1. # Time: O(logn) = O(1)
  2. # Space: O(logn) = O(1)
  3. class Solution(object):
  4. def nextGreaterElement(self, n):
  5. """
  6. :type n: int
  7. :rtype: int
  8. """
  9. digits = map(int, list(str(n)))
  10. k, l = -1, 0
  11. for i in xrange(len(digits) - 1):
  12. if digits[i] < digits[i + 1]:
  13. k = i
  14.  
  15. if k == -1:
  16. digits.reverse()
  17. return -1
  18.  
  19. for i in xrange(k + 1, len(digits)):
  20. if digits[i] > digits[k]:
  21. l = i
  22.  
  23. digits[k], digits[l] = digits[l], digits[k]
  24. digits[k + 1:] = digits[:k:-1]
  25. result = int("".join(map(str, digits)))
  26. return -1 if result >= 0x7FFFFFFF else result

C++:  

  1. class Solution {
  2. public:
  3. int nextGreaterElement(int n) {
  4. string str = to_string(n);
  5. int len = str.size(), i = len - 1;
  6. for (; i > 0; --i) {
  7. if (str[i] > str[i - 1]) break;
  8. }
  9. if (i == 0) return -1;
  10. for (int j = len - 1; j >= i; --j) {
  11. if (str[j] > str[i - 1]) {
  12. swap(str[j], str[i - 1]);
  13. break;
  14. }
  15. }
  16. sort(str.begin() + i, str.end());
  17. long long res = stoll(str);
  18. return res > INT_MAX ? -1 : res;
  19. }
  20. };

C++:

  1. /**
  2. * 1. a max number has the property of decreasing in every digit: 9876
  3. * 2. find the first non-max substring from the right; ex. in 1234(59876), 59876 is the first non-max substring from the right
  4. * 3. sort the max part of 5(9876), by reverse, becames 5(6789);
  5. * 4. flip 5,6, becames 65789; because 6 is the next smallest digit than 5, in 56789;
  6. * 5. incase of 66789, you got flip 6 with 7 to make it 76689, to make it bigger.
  7. */
  8. class Solution {
  9. public:
  10. int nextGreaterElement(int n) {
  11. string s = to_string(n);
  12. if (s.length() == 1) {
  13. return -1;
  14. }
  15. /* find the first decreasing digit from the right, eg: 59876, 5 is the first decreasing digit */
  16. int i = s.length() - 2; // 21 -> i = 0; 59876 -> i = 3
  17. for (; i >= 0 && s[i] >= s[i + 1]; i--) { }
  18. if (i == -1) { // if a decreasing digit cannot be find, the number cannot be larger.
  19. return -1;
  20. }
  21. reverse(s.begin() + i + 1, s.end());
  22. for (int j = i + 1; j < s.length(); j++) {
  23. if (s[j] > s[i]) {
  24. swap(s[i], s[j]);
  25. break;
  26. }
  27. }
  28. long next = stol(s);
  29. return next == n || next > INT_MAX ? -1 : next;
  30. }
  31. };

C++: using next permutation

  1. int nextGreaterElement(int n) {
  2. auto digits = to_string(n);
  3. next_permutation(begin(digits), end(digits));
  4. auto res = stoll(digits);
  5. return (res > INT_MAX || res <= n) ? -1 : res;
  6. }

  

类似题目:

[LeetCode] 496. Next Greater Element I 下一个较大的元素 I

[LeetCode] 503. Next Greater Element II 下一个较大的元素 II

All LeetCode Questions List 题目汇总

[LeetCode] 556. Next Greater Element III 下一个较大的元素 III的更多相关文章

  1. [LeetCode] 496. Next Greater Element I 下一个较大的元素 I

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...

  2. [LeetCode] 503. Next Greater Element II 下一个较大的元素 II

    Given a circular array (the next element of the last element is the first element of the array), pri ...

  3. [LeetCode] Next Greater Element II 下一个较大的元素之二

    Given a circular array (the next element of the last element is the first element of the array), pri ...

  4. Leetcode496.Next Greater Element I下一个更大的元素1

    给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集.找到 nums1 中每个元素在 nums2 中的下一个比其大的值. nums1 中数字 x 的下一个更 ...

  5. [leetcode]496. Next Greater Element I下一个较大元素

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...

  6. lintcode-1174.下一个更大的元素 III

    题目描述: 1174. 下一个更大的元素 III 给定一个32位整数n,用同样的数字组成新的32位整数,使得它要比n大,返回最小的这样的数.如果不存在这样的整数,返回-1. 算法思路: 首先将这个数转 ...

  7. 503 Next Greater Element II 下一个更大元素 II

    给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素.数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它 ...

  8. 496 Next Greater Element I 下一个更大元素 I

    给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集.找到 nums1 中每个元素在 nums2 中的下一个比其大的值.nums1 中数字 x 的下一个更大 ...

  9. [LeetCode] Next Greater Element I 下一个较大的元素之一

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...

随机推荐

  1. django项目基于钩子验证的注册功能

    前端html <div class="agile-row"> <h3>注册</h3> {# 注册的开始#} <div class=&quo ...

  2. O(n) 取得数组中每个元素右边第一个比它大的元素

    题目: 给定一个整型数组,数组元素随机无序的,要求打印出所有元素右边第一个大于该元素的值. 如数组A=[6,8,9,2,3,5,6] 输出[8,9,-1,3,5,6,-1] 思路: 我们用栈来保存未找 ...

  3. 利用SQL直接生成模型实体类

    在网上找来一个别人写好的,生成实体类的SQL代码 declare @TableName sysname = 'lkxxb' declare @Result varchar(max) = 'public ...

  4. 深度学习Keras框架笔记之AutoEncoder类

    深度学习Keras框架笔记之AutoEncoder类使用笔记 keras.layers.core.AutoEncoder(encoder, decoder,output_reconstruction= ...

  5. Python开发笔记:网络数据抓取

    网络数据获取(爬取)分为两部分: 1.抓取(抓取网页) · urlib内建模块,特别是urlib.request · Requests第三方库(中小型网络爬虫的开发) · Scrapy框架(大型网络爬 ...

  6. IntelliJ IDEA 2019.2破解

    IntelliJ IDEA 2019.2破解 我是参考这个激活的,使用的激活码的方式,需要在百度云盘下载压缩包 https://zhile.io/2018/08/25/jetbrains-licens ...

  7. 【Spring】如何配置多个applicationContext.xml文件

    在web.xml中通过contextConfigLocation配置spring 开发Java Web程序,使用ssh架构时,默认情况下,Spring的配置文件applicationContext.x ...

  8. npm包之npm-check-updates

    检查npm的依赖包是否有比较新的版本 安装 npm i -g npm-check-updates 使用 ncu --help // 查看相关命令 ncu // 检查当前项目中有没有哪些依赖包可更新 n ...

  9. 浏览器报400-Bad Request异常

    今天在使用ie浏览器在测试程序的时候,报这个错误,后台日志打印出来显示的是:连接一个远程主机失败 解决Invalid character found in the request target. Th ...

  10. 2019.12.06 java基础

    JRE:运行环境(包含JVM(Java Virtual Machine)- Java虚拟机和核心类库) JDK: JAVA语言的软件开发工具包(Java Development Kit) Dos命令行 ...