532. K-diff Pairs in an Array

 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     int findPairs(vector<int>& nums, int k) 
12     {
13         if(k<0)
14             return 0;
15         unordered_map<int,int> imap;
16         int res=0;
17         for(int i:nums)
18             imap[i]++;
19         if(k==0)
20         {
21             for(auto p:imap)
22             {
23                 if(p.second>1)
24                     res++;
25             }
26         }
27         else
28         {
29             for(auto p:imap)
30             {
31                 if(imap.find(p.first+k)!=imap.end())
32                     res++;
33             }
34         }
35         return res;
36     }
37 };

用一个关联容器将数组元素都扫描进去,再根据k的值分类判定

值得注意的是,判定一个元素是否在关联容器中,find()的性能优于count()。

猜你喜欢

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