统计一个数字在排序数组中出现的次数。
利用函数
lower_bound()和upper_bound()是STL函数。
效果是,以二分查找的方式,进行所选位置之间的特定值查找,返回的是第一个值的
lower_bound(ite1,ite2,target)。lower是找到第一个。
upper是找到最后一个。
另外,不能用int接住迭代器,但是迭代器的差,却可以用int接住。
class Solution {
public:
int search(vector<int>& nums, int target) {
int a=lower_bound(nums.begin(),nums.end(),target)-nums.begin();
int b=upper_bound(nums.begin(),nums.end(),target)-nums.begin();
return b-a;
}
};
vector<int>::iterator a = lower_bound(vec.begin(), vec.end(), 6);
int a = lower_bound(vec.begin(), vec.end(), 6);
int a = lower_bound(vec.begin(), vec.end(), 6) - vec.begin();
由此可知,lower_bound和upper_bound的返回值是迭代器,也就是对应位置的指针。
哈希表
这个方法是我自己写的,但是可能是会有空间消耗。不能作为最好的答案。
class Solution {
public:
int search(vector<int>& nums, int target) {
unordered_map<int,int>hp;
for(auto& x:nums)++hp[x];
auto ite=hp.find(target);
if(ite!=hp.end())return hp.find(target)->second;
else return 0;
}
};
时间和空间都是O(n)。