zoukankan      html  css  js  c++  java
  • leetcode556—— Next Greater Element III (JAVA)

    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 n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

    Example 1:

    Input: 12
    Output: 21
    

    Example 2:

    Input: 21
    Output: -1
    转载注明出处:http://www.cnblogs.com/wdfwolf3/,谢谢。
    时间复杂度O(n),空间复杂度O(n),5ms。
    public int nextGreaterElement(int n){
            //如果是1位整数,直接返回-1,同时加上了10和11
            if(n <= 11){
                return -1;
            }
            //转化为char数组,方便处理数字
            char[] nums = (n+"").toCharArray();
            int i = nums.length - 2;
            //从后往前找到第一个升序的位数
            for (; i >= 0; i--) {
                if (nums[i] < nums[i+1]) {
                    break;
                }
            }
            //如果没有即不存在,返回-1
            if(i < 0){
                return -1;
            }
            int j = nums.length -1;
            //从后往前查找第一个比i大的数字,这样找出来的是所有大于i数字中的最小值
            for (; j > i; j--) {
                if(nums[i] < nums[j]){
                    break;
                }
            }
            //交换i,j位置的数字
            char tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
            //i之后的数字排序,让结果最小
            Arrays.sort(nums, i, nums.length);
            //有可能交换后越界,使用long类型判断一下
            long ans = Long.parseLong(new String(nums));
            return (ans>Integer.MAX_VALUE)?-1:((int)ans);
        }
     
  • 相关阅读:
    HTML5标签变化
    接口测试基础入门学习
    1.1Axure简介
    win 7命令行大全
    程序集强签名
    源代码的文件头格式化
    redmine2.3环境搭建
    静态成员和方法的使用场合及利弊分析
    .Net Memory Profiler入门
    TransactionScope类
  • 原文地址:https://www.cnblogs.com/wdfwolf3/p/6837445.html
Copyright © 2011-2022 走看看