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;
}
数组A中给定可以使用的1~9的数,返回由A数组中的元素组成的小于n的最大数。例如A={1, 2, 4, 9},x=2533,返回2499
于 2022-05-10 16:34:18 首次发布