C++ 二分查找(查询指定首字母出现的第一个位置)

C++ 二分查找查询指定首字母出现的第一个位置

如果输入b,就代表查询首字母为b出现的第一个位置,即0

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string words[] = {"b", "bb", "ce", "dc", "de"};

int _find(int l, int r, char ch) {
    if (l >= r) {
        if (words[l][0] == ch) {
            return l;
        } else {
            return -1;
        }
    }
    int mid = (l + r) / 2;
    if (ch <= words[mid].at(0)) {
        return _find(l, mid, ch);
    } else {
        return _find(mid + 1, r, ch);
    }
}


int main() {
	char ch;
	sort(words.begin(), words.end()); 
	while (cin >> ch)
		cout << _find(0, 4, ch) << endl;
}


本文标题:《C++ 二分查找(查询指定首字母出现的第一个位置)》作者:Scar
原文链接:https://aki.cc/post/3.html
特别注明外均为原创,转载请注明。

分享到微信

扫描二维码

可在微信查看或分享至朋友圈。

相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。