2024华为OD机试题库-(A卷+B卷+C卷+D卷)-(JAVA、Python、C++)
2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++)
题目描述
小朋友出操,按学号从小到大排成一列;小明来迟了,请你给小明出个主意,让他尽快找到他应该排的位置。
算法复杂度要求不高于 nLog(n);
学号为整数类型,队列规模<=10000;
输入描述
1、第一行:输入已排成队列的小朋友的学号(正整数),以”,”隔开;
例如:93,95,97,100,102,123,155
2、第二行:小明学号,如 110;
输出描述
输出一个数字,代表队列位置(从 1 开始)。
例如:
6
示例1
输入
93,95,97,100,102,123,155
110
输出
6
示例2
输入
93,95,97,100,102,123,155
90
输出
1
示例3
输入
93,95,97,100,102,123,155
160
输出
8
考点
二分查找
解题思路
将已排好序的学号列表转换成整数列表,然后使用二分查找找到小明应该插入的位置
代码
c++
#include <bits/stdc++.h>
using namespace std;
int main() {
int tmp,cur;
vector<int> vec;
while(cin>>tmp) {
vec.push_back(tmp);
if(cin.get()=='\n') {break;}
}
cin>>cur;
int hi=vec.size()-1;
int low=0, mid; //下标最大最小值
if(cur<vec[0]) {
cout<<1<<endl;
}else if(cur>vec[hi]) {
cout<<vec.size()+1<<endl;
}else{
while(hi-low>1) {
mid=ceil((hi+low)/2);
if(vec[mid]<cur) {
low=mid;
}else{
hi=mid;
}
}
cout<<hi+1<<endl;
}
system("pause");
return 0;
}
java
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nums = Arrays.stream(sc.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
int target = Integer.parseInt(sc.nextLine());
int idx = Arrays.binarySearch(nums, target);
if (idx < 0) {
idx = -idx - 1;
}
System.out.println(idx + 1);
}
}
python
vec=list(map(int,input().split(',')))
tar=int(input()) #目标学号
l