栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣:556. 下一个更大元素 III

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣:556. 下一个更大元素 III


import java.util.Arrays;


public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.nextGreaterElement(230241));
    }

    public int nextGreaterElement(int n) {
        // 转换成字符串
        char[] chars = Integer.toString(n).toCharArray();
        int i = chars.length - 2;
        while (i >= 0 && chars[i] >= chars[i + 1]){
            i--;
        }
        if (i < 0){
            return -1;
        }
        int j = chars.length - 1;
        // 从后面开始找,找到比i值大的数
        while (j >= 0 && chars[i] >= chars[j]){
            j--;
        }

        // 替换两个的位置
        swap(chars, i, j);
        // 把后面的结果重新排序
        Arrays.sort(chars, i + 1, chars.length );
        long l = Long.parseLong(new String(chars));
        return l > Integer.MAX_VALUE ? -1 : (int)l;

    }

    private void swap(char[] arr, int i, int j){
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
package com.算法专练.力扣.下一个更大元素III;

import java.util.Arrays;


public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.nextGreaterElement(230241));
    }

    public int nextGreaterElement(int n) {
        // 转换成字符串
        char[] chars = Integer.toString(n).toCharArray();
        int i = chars.length - 2;
        while (i >= 0 && chars[i] >= chars[i + 1]){
            i--;
        }
        if (i < 0){
            return -1;
        }
        int j = chars.length - 1;
        // 从后面开始找,找到比i值大的数
        while (j >= 0 && chars[i] >= chars[j]){
            j--;
        }

        // 替换两个的位置
        swap(chars, i, j);
        // 把后面的结果重新排序
        Arrays.sort(chars, i + 1, chars.length );
        long l = Long.parseLong(new String(chars));
        return l > Integer.MAX_VALUE ? -1 : (int)l;

    }

    private void swap(char[] arr, int i, int j){
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003564.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号