数组A中给定可以使用的1~9的数,返回由A数组中的元素组成的小于n的最大数。例如A={1, 2, 4, 9},x=2533,返回2499

public static void main(String[] args) {
        int[] nums = {2,4,9};
        int res = MaxNumberLessThanN(nums, 2215);
        System.out.println(res);
    }

    public static int MaxNumberLessThanN(int[] nums, int x) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        char[] chars = (x + "").toCharArray();
        int[] resIndex = new int[chars.length];
        int i, j;
        boolean flag = false;
        for (i = 0; i < chars.length; i++) {
            int cur = chars[i] - '0';
            for (j = nums.length - 1; j >= 0; j--) {
                if (flag) {
                    resIndex[i] = j;
                    break;
                } else if (cur == nums[j]) {
                    resIndex[i] = j;
                    break;
                } else if (cur > nums[j]) {//解决中间某数小于当前位上数,之后所有位置上数取最大值
                    resIndex[i] = j;
                    flag = true;
                    break;
                }
            }
            if (j == -1) {
                if (i == 0) {//解决第一数无法取到最小值问题
                    resIndex[i] = -1;
                } else {
                    int pre = i;
                    while (pre > 0 && resIndex[pre] == 0) {//解决[2,4,9],24215问题
                        resIndex[pre] = nums.length - 1;
                        pre--;
                    }
                    resIndex[pre]--;
                }
                flag = true;
            }
        }
        int ans = 0;
        int index = resIndex[0] == -1 ? 1 : 0;
        while (index < chars.length) {
            ans = ans * 10 + nums[resIndex[index]];
            index++;
        }
        if (ans==x){//解决[2,4,9],2499问题
            int m = resIndex.length-1;
            while (m>=0&&resIndex[m]==0){
                m--;
            }
            resIndex[m]--;
            index = resIndex[0] == -1 ? 1 : 0;
            ans = 0;
            while (index < chars.length) {
                ans = ans * 10 + nums[resIndex[index]];
                index++;
            }
        }
        return ans;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值