217. Contains Duplicate

找重复元素,两种方法

第一种:排序,有重复元素,必然出现在相邻位置

 1 int x=[](){
 2     std::ios::sync_with_stdio(false);
 3     cin.tie(NULL);
 4     return 0;
 5 }();
 6 
 7 class Solution
 8 {
 9 public:
10     bool containsDuplicate(vector<int>& nums)
11     {
12         int size = nums.size();
13         if(size <= 1) return false;
14         sort(nums.begin(), nums.end());
15         for(int i = 0; i < size-1; ++i)
16         {
17             if(nums[i] == nums[i+1]) return true;
18         }
19         return false;
20     }
21 
22 };

第二种:利用关联容器计数,计数值大于1,必然有重复元素。

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     bool containsDuplicate(vector<int>& nums) 
12     {
13         unordered_map<int,int> vmap;
14         for(int i : nums)
15         {
16             vmap[i]++;
17             if(vmap[i]>1)
18                 return true;
19         }
20         return false;
21     }
22 };

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9077157.html