华为机考真题 -- 小明找位置

题目描述:

小朋友出操,按学号从小到大排成一列;小明来迟了,请你给小明出个主意,让他尽快找到他应该排的位置。算法复杂度要求不高于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

C++源码:

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;

int main() {
    string line;
    getline(cin, line); // 读取第一行的学号序列
    vector<int> queue;

    stringstream ss(line);
    int num;
    while (ss >> num) {
        queue.push_back(num);
        if (ss.peek() == ',') ss.ignore();
    }

    int ming; // 小明的学号
    cin >> ming;

    // 使用二分查找法找到小明的位置
    auto it = lower_bound(queue.begin(), queue.end(), ming);
    int position = it - queue.begin() + 1; // 计算队列位置(从1开始)

    cout << position << endl;

    system("pause");
    return 0;
}
相关推荐
木斯佳32 分钟前
HarmonyOS 6实战(源码教学篇)— Speech Kit TextReader:【仿某云音乐接入语音朗读控件】
华为·harmonyos
2501_9403152640 分钟前
航电oj:首字母变大写
开发语言·c++·算法
lhxcc_fly1 小时前
手撕简易版的智能指针
c++·智能指针实现
CodeByV1 小时前
【算法题】多源BFS
算法
TracyCoder1231 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居1 小时前
泛型编程与STL设计思想
开发语言·c++·算法
南村群童欺我老无力.1 小时前
Flutter 框架跨平台鸿蒙开发 - 校园生活一站式:打造智慧校园服务平台
flutter·华为·harmonyos
Fcy6481 小时前
C++ 异常详解
开发语言·c++·异常
机器视觉知识推荐、就业指导2 小时前
Qt 和 C++,是不是应该叫 Q++ 了?
开发语言·c++·qt
独处东汉2 小时前
freertos开发空气检测仪之输入子系统结构体设计
数据结构·人工智能·stm32·单片机·嵌入式硬件·算法