文章目录
一、35. 搜索插入位置
1.原题链接
2.题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(log n) 的算法。
3.解题思路
二分查找
4.源码
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
int ans=nums.size();
while(l<=r){
int mid=(l+r)>>1;
if(nums[mid]>=target){
ans=mid;
r=mid-1;
}
else{
l=mid+1;
}
}
return ans;
}
};
二、704. 二分查找
1.原题链接
2.题目描述
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
3.解题思路
二分查找即可。
4.源码
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size();
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] > target) {
right = mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
};
三、剑指 Offer 53 - I. 在排序数组中查找数字 I
1.原题链接
2.题目描述
统计一个数字在排序数组中出现的次数。
3.解题思路
二分查找,找到与target相同的累加即可。
4.源码
class Solution {
public:
int search(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
int ans=0;
while(l<=r){
int mid=(l+r)>>1;
if(nums[mid]>=target){
r=mid-1;
}
else {
l=mid+1;
}
}
while(l<nums.size()&&nums[l++]==target){
ans++;
}
return ans;
}
};
四、911. 在线选举
1.原题链接
2.题目描述
给你两个整数数组 persons 和 times 。在选举中,第 i 张票是在时刻为 times[i] 时投给候选人 persons[i] 的。对于发生在时刻 t 的每个查询,需要找出在 t 时刻在选举中领先的候选人的编号。在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。
实现 TopVotedCandidate 类:
TopVotedCandidate(int[] persons, int[] times) 使用 persons 和 times 数组初始化对象。
int q(int t) 根据前面描述的规则,返回在时刻 t 在选举中领先的候选人的编号。
3.解题思路
预处理+二分查找,预处理每个时间段得到票数最多的人,运用二分查找对于小于等于给定时间t 的最大下标,并通过下标找到获胜者。
4.源码
class TopVotedCandidate {
public:
vector<int> tops;
vector<int> times;
TopVotedCandidate(vector<int>& persons, vector<int>& times) {
unordered_map<int,int> count;
count[-1]=-1;
int top =-1;
for(auto &p :persons){
count[p]++;
if(count[p]>=count[top]){
top=p;
}
tops.emplace_back(top);
}
this->times=times;
}
int q(int t) {
int pos = upper_bound(times.begin(), times.end(), t) - times.begin() - 1;
return tops[pos];
}
};
总结
第九天,在线选举这题还需要再思考一下。