> 文章列表 > STL学习+acwing 67 数字在排序数组中出现的次数

STL学习+acwing 67 数字在排序数组中出现的次数

STL学习+acwing 67 数字在排序数组中出现的次数

题目链接
67. 数字在排序数组中出现的次数
STL学习+acwing 67 数字在排序数组中出现的次数

传统暴力解法

class Solution {
public:int getNumberOfK(vector<int>& nums , int k) {int c=0;for(int i=0;i<nums.size();i++){if(nums[i]==k)c++;}return c;}
};

容器的应用

set和multiset两个容器有一个count函数

set 为有序集合,不允许有重复的元素
multise为有序多重集合,可以有重复的元素
这个题应该选multiset

inserts.insert(x)把一个元素x插入到集合s中,时间复杂度为O(logn)。在set中,若元素已存在,则不会重复插入该元素,对集合的状态无影响。counts.count(x) 返回集合s中等于x的元素个数,时间复杂度为 O(k +logn),其中k为元素x的个数。
class Solution {
public:int getNumberOfK(vector<int>& nums , int k) {multiset<int>m;for(int i=0;i<nums.size();i++){m.insert(nums[i]);}return m.count(k);}
};

这个count 函数也可以用于vector

也可以用lower_bound()或者是
在STL(标准模板库)中,lower_bound(x)是一个函数模板,用于查找有序容器中第一个不小于给定值x的元素位置。

lower_bound 函数是 C++ STL 中的一个算法,它用于在有序容器中查找第一个大于或等于给定值的元素。它适用于以下容器:std::vectorstd::dequestd::liststd::forward_liststd::arraystd::setstd::multisetstd::mapstd::multimap需要注意的是,由于 lower_bound 函数要求容器必须是有序的,因此对于不支持有序操作的容器(如 std::unordered_set 和 std::unordered_map),它是不适用的。

并且这个函数的类型是迭代器类型
STL学习+acwing 67 数字在排序数组中出现的次数STL学习+acwing 67 数字在排序数组中出现的次数对不起,我没学过容器,所以你可以当我是个傻子。

可以用auto这个C++11 的新特性

它是一种类型推导关键字,可以让编译器自动推导变量的类型,从而简化代码。
auto 还可以用于迭代器、lambda 表达式等场合,进一步提高代码的可读性和灵活性。

class Solution {
public:int getNumberOfK(vector<int>& nums , int k) {auto l=lower_bound(nums.begin(),nums.end(),k);auto h=upper_bound(nums.begin(),nums.end(),k);return h-l;}
};