码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode556—— Next Greater Element III (JAVA)

时间:2017-05-10 19:47:08      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:color   tco   []   log   .so   str   next   integer   位置   

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);
    }

 

 

leetcode556—— Next Greater Element III (JAVA)

标签:color   tco   []   log   .so   str   next   integer   位置   

原文地址:http://www.cnblogs.com/wdfwolf3/p/6837445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!