【LeetCode】738. Monotone Increasing Digits 单调递增的数字(Medium)(JAVA)每日一题

【LeetCode】738. Monotone Increasing Digits 单调递增的数字(Medium)(JAVA)

题目地址: https://leetcode-cn.com/problems/monotone-increasing-digits/

题目描述:

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

Example 1:

Input: N = 10
Output: 9

Example 2:

Input: N = 1234
Output: 1234

Example 3:

Input: N = 332
Output: 299

Note: N is an integer in the range [0, 10^9].

题目大意

给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。

(当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。)

解题方法

  1. 这一题就是从头开始往后遍历,如果遇到不是单调递增的位数如 xxx32xx, 32 就不是单调递增的,就停止向后遍历
  2. 32 的 3 开始往前遍历,如果 xxx3 的前面是等于 3 的,就继续遍历,直到最前面或者不等于 3 为止,然后当前位数 -1,后面的全部变为 9,如果第一位是 0 ,要去掉
  3. 如:123332, 遍历到 32 的 32 停止,3 开始往前遍历,到 23 的 3 停止,3-1 变为 2,后面都为 9: 122999
class Solution {
    public int monotoneIncreasingDigits(int N) {
        if (N < 10) return N;
        int copy = N;
        List<Integer> list = new ArrayList<>();
        while (copy > 0) {
            list.add(0, copy % 10);
            copy /= 10;
        }

        int chang = -1;
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i) > list.get(i + 1)) {
                chang = i;
                break;
            }
        }
        if (chang < 0) return N;
        while (chang > 0 && list.get(chang - 1) == list.get(chang)) {
            chang--;
        }
        list.set(chang, list.get(chang) - 1);
        for (int i = chang + 1; i < list.size(); i++) {
            list.set(i, 9);
        }
        if (list.get(0) == 0) list.remove(0);
        int res = 0;
        for (int i = 0; i < list.size(); i++) {
            res = res * 10 + list.get(i);
        }
        return res;
    }
}

执行耗时:2 ms,击败了32.32% 的Java用户
内存消耗:35.3 MB,击败了79.18% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值