当前位置:网站首页>小于n的最大数
小于n的最大数
2022-07-27 15:08:00 【折叠的饼干】
给一个数组nums=[5,4,8,2],给一个n=5416, 让你从nums中选出一些元素,使得组成的数字是小于n的最大数
思路:贪心+二分查找
遍历n的各位上的数,找到数组中不存在的数的最高位
该位之前不变,该位改为小于n的该位的最大值,其余位为nums里最大值
如果都存在,则修改最低位
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//找小于idex的的最后一个
int searchl(vector<int>nums,int target){
int l=0,r=nums.size()-1;
while(l<r){
int mid=l+r+1>>1;
if(nums[mid]<target)l=mid;
else r=mid-1;
}
if(nums[l]<target)return nums[l];
else return -1;
}
//找小于等于idex的最后一个
int searchle(vector<int>nums,int target){
int l=0,r=nums.size()-1;
while(l<r){
int mid=l+r+1>>1;
if(nums[mid]<=target)l=mid;
else r=mid-1;
}
if(nums[l]<=target)return nums[l];
else return -1;
}
int main(){
vector<int>nums={
1,1,1};
int n=1234;
vector<int>maxn,ans;
sort(nums.begin(),nums.end());
while(n){
maxn.push_back(n%10);
n/=10;
}
int len=maxn.size();
int h=len;
for(int i=len-1;i>=0;i--){
int idx=searchle(nums,maxn[i]);
// printf("maxi=%d,idx=%d\n",maxn[i],idx);
if(idx!=maxn[i]){
h=i;
break;
}
}
if(h>=0){
for(int i=len-1;i>=0;i--){
if(i>h)ans.push_back(maxn[i]);
else if(i==h)ans.push_back(searchl(nums,maxn[i]));
else ans.push_back(nums[nums.size()-1]);
}
}else{
for(int i=len-1;i>=1;i--){
ans.push_back(maxn[i]);
}
ans.push_back(searchl(nums,maxn[0]));
}
for(int i=0;i<ans.size();i++){
printf("%d\n",ans[i]);
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
.net core with microservices - what is a microservice
Day07 operation
高精度定时器
全局String对象(函数类型)+Math对象
下棋机器人折断7岁男孩手指,网友:违反了机器人第一定律
C语言之字符函数和字符串函数及内存函数
两表联查1
Log4j.jar and slf4-log4 download link
Measured: the performance of cloud RDS MySQL is 1.6 times that of self built
Redis: 配置AOF不起作用
C语言之函数
Niuke topic -- symmetric binary tree
Motion capture system for end positioning control of flexible manipulator
今日睡眠质量记录82分
Random number formula random
Getting started with unity
Passive income: return to the original and safe two ways to earn
Jerry's in ear detection function [chapter]
大厂们终于无法忍受“加一秒”了,微软谷歌Meta等公司提议废除闰秒
C语言之数组









