给一个数组和一个数字n,数组里面是0到9的数字,求数组里面的数字组成的不大于n的最大数字是多少
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
//将剩余位全部设置为数组里的最大值
void getmax(stack<int>& sres, int value, int count){
for(int i = 0; i < count; i++){
sres.push(value);
}
}
//二分查找,取得小于等于传入值的最大值
int getindex(vector<int>& vec, int value){
int left = 0, right = vec.size()-1, target = -1;
while(left <= right){
int mid = (right-left) / 2 + left;
if(vec[mid] > value){
right = mid-1;
}else if(vec[mid] < value){
target = mid;
left = mid + 1;
} else {
return mid;
}
}
return target;
}
//主函数
int helper(vector<int>& vec, string s){
int n = vec.size();
stack<int>sres;
int ssize = s.size();
for(int i = 0; i < ssize; i++){
int countnum = s[i] - '0';
int index = getindex(vec, countnum);
//如果当前位置的值比数组的所有位置都要小,栈要进行弹出操作,相当于去回溯
if(index == -1){
while(!sres.empty()){
int top = sres.top();
sres.pop();
int tmpindex = getindex(vec, top-1);
if(tmpindex == -1)
continue;
sres.push(vec[tmpindex]);
break;
}
if(sres.empty())
getmax(sres, vec[n-1], ssize-1);
else
getmax(sres, vec[n-1], ssize - sres.size());
break;
}else if(vec[index] == countnum){
//若是相等,就加进去
sres.push(countnum);
}else if(vec[index] < countnum){
//若是二分查找的值于当前值并不相等,那么把二分查找的值加入,并且后面的值全取数组的最大值
sres.push(vec[index]);
getmax(sres, vec[n-1],ssize-i-1);
break;
}
}
int res = 0, count = 1;
while(!sres.empty()){
res += sres.top() * count;
count *= 10;
sres.pop();
}
return res;
}
int main() {
int a[1] = {3};
vector<int> vec(a, a+1);
string x = "1111";
sort(vec.begin(), vec.end());
//传入的值是x-1
std::cout << helper(vec, x) << std::endl;
return 0;
}