最近看大家面经总有一道常见的题目:   数组A中给定可以使用的1~9的数,返回由A数组中的元素组成的小于n的最大数。例如A={1, 2, 4, 9},n=2533,返回2499有两个常见思路:1.暴力递归回溯,最后判断;2.贪心思想。 其中第二个思路比较有争议,看讨论大家好像也没有很统一的想法,先贴一下自己的代码 #include <iostream>#include <stack>#include <string>#include <vector>using namespace std;int n, x;//将剩余位全部设置为数组里的最大值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){    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){            int tmpcount = 0;            while(!sres.empty()){                int top = sres.top();                sres.pop();                int tmpindex = getindex(vec, top-1);                if(tmpindex == -1)                    continue;                sres.push(vec[tmpindex]);                tmpcount++;                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() {    cin >> n;    vector<int> vec(n);    for(int i = 0; i < n; i++)        cin >> vec[i];    cin >> x;    sort(vec.begin(), vec.end());    //传入的值是x-1    std::cout << helper(vec, to_string(x-1)) << std::endl;    return 0;}我觉得这个代码是正确的,希望大家可以指正一下, 我自己编造的例子基本都过了。
点赞 11
评论 9
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务