当前位置:网站首页>小于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
- JDBC connection database
- 三表联查1
- Database foundation
- 关于 SAP UI5 应用 ui5.yaml 里的 paths 映射问题
- 下棋机器人折断7岁男孩手指,网友:违反了机器人第一定律
- Unity 入门
- LNMP环境--部署wordpress
- Niuke topic -- Realizing queues with two stacks, stacks containing min functions, and valid bracket sequences
猜你喜欢

下棋机器人折断7岁男孩手指,网友:违反了机器人第一定律

国产新冠口服药为什么是治艾滋病的药

大厂们终于无法忍受“加一秒”了,微软谷歌Meta等公司提议废除闰秒

day07 作业

JDBC connection database

Reference of meta data placeholder

ES6数组新增属性

SAP UI5 FileUploader 的本地文件上传技术实现分享

Motion capture system for end positioning control of flexible manipulator

Measured: the performance of cloud RDS MySQL is 1.6 times that of self built
随机推荐
Functions in JS
合工大苍穹战队视觉组培训Day7——视觉,jetson naon与D435i
Global string object (function type) +math object
UITableView 基本使用和优化
High precision timer
Servlet Chinese garbled setcontenttype setting is invalid
每条你收藏的资讯背后,都离不开TA
Jerry's built-in touch parameters for modification [chapter]
Database foundation
牛客题目——对称的二叉树
How does vs2019 C language run multiple projects at the same time, how to add multiple source files containing main functions in a project and debug and run them respectively
国产新冠口服药为什么是治艾滋病的药
New attributes of ES6 array
动作捕捉系统用于柔性机械臂的末端定位控制
Xcode releases test package testflight
Jerry's in ear detection function [chapter]
移动端基础
随机数公式Random
项目练习:表格的查改功能
Servlet中文乱码setContentType设置无效