当前位置:网站首页>小于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;
}
边栏推荐
- URL 返回nil 以及urlhash处理
- Understand the basic properties of BOM and DOM
- C语言之函数
- JD Zhang Zheng: practice and exploration of content understanding in advertising scenes
- 下棋机器人折断7岁男孩手指,网友:违反了机器人第一定律
- 被动收入:回归原始且安全的两种赚取方法
- LNMP环境--部署wordpress
- 牛客题目——最小的K个数
- 渐变环形进度条
- Passive income: return to the original and safe two ways to earn
猜你喜欢

This large model sparse training method with high accuracy and low resource consumption has been found by Alibaba cloud scientists! Has been included in IJCAI

Getting started with nvida CUDA dirverapi

Global string object (function type) +math object

C语言之动态内存分配

Dynamic memory allocation in C language

三表联查2

Complete steps of JDBC program implementation

meta-data 占位符的引用

Niuke topic - parity rearrangement of linked list, right view of output binary tree, bracket generation, first non repeating character in character stream

Data collection: skillfully using Bloom filter to extract data summary
随机推荐
一个端到端的基于 form 表单的文件上传程序,包含客户端和服务器端
Swift QQ授权登录 坑集
Passive income: return to the original and safe two ways to earn
Servlet Chinese garbled setcontenttype setting is invalid
log4j.jar和slf4-log4下载链接
C语言之操作符
mysql视图及存储过程
JDBC连接数据库
高精度定时器
High precision timer
Advanced pointer of C language
Day 7 summary & homework
今日睡眠质量记录82分
C语言之指针初级
SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细
Understand the basic properties of BOM and DOM
牛客题目——用两个栈实现队列、包含min函数的栈、有效括号序列
Gartner 权威预测未来4年网络安全的8大发展趋势
选 择 结 构
JDBC connection database