问题
代码
大神代码
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right = n - 1, ans = n;
while (left <= right) {
int mid = ((right - left) >> 1) + left;
if (target <= nums[mid]) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
};
小白的例题代码
// 算法竞赛入门经典系列源码解析
// 算法竞赛入门经典第2版
// 算法竞赛入门经典 习题与解答
// 算法竞赛入门经典 训练指南
// 算法竞赛入门经典 算法实现
// 力扣练习
//
// C++ Primer 第5版 P100
/*
Dreams never shine!
It's you that shine while chasing your dreams :)
JAYO!!
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> text;
int n;
string tmp;
cin >> n;
while (n--) {
cin >> tmp;
text.push_back(tmp);
}
sort(text.begin(), text.end());
for (auto m : text) cout << m << " ";
cout << endl;
// Binary Search
string sought;
cin >> sought;
// text 必须是有序的
// beg 和 end 表示我们搜索的范围
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg) / 2; // 初始状态下的中间点(迭代器可以相减,不能相加,错误示范:mid = (beg + end) / 2)
// 当还有元素尚未检查并且我们还没有找到 sought 时执行循环
while (mid != end && * mid != sought) {
if (sought < * mid) // 我们要找的元素在前半部分吗?
end = mid; // 如果是,调整搜索范围使得忽略掉后半部分
else // 我们要找的元素在后半部分
beg = mid + 1; // 在 mid 之后寻找
mid = beg + (end - beg) / 2; // 新的中间点
}
if (* mid == sought) cout << "Yes!\n";
else cout << "No!\n";
return 0;
}
总结
珍惜时间,朝着目标前进!10h Today!