AcWing 67. 数字在排序数组中出现的次数
原题链接
简单
1.for循环遍历
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
int cnt=0;
for(auto i=nums.begin();i<nums.end();++i)
if(*i==k)
cnt++;
return cnt;
}
};
2.multiset count
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
multiset<int> ans;
for(auto i : nums)
ans.insert(i);
return ans.count(k);
}
};
3.lower_bound,upper_bound
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
auto l = lower_bound(nums.begin(), nums.end(), k);
auto r = upper_bound(nums.begin(), nums.end(), k);
return r-l;
}
};
4.count
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
return count(nums.begin(), nums.end(), k);
}
};