532 K-diff Pairs in an Array 数组中差为K的数对

详见:https://leetcode.com/problems/k-diff-pairs-in-an-array/description/

C++:

class Solution {
public:
    int findPairs(vector<int>& nums, int k) 
    {
        int res = 0, n = nums.size();
        unordered_map<int, int> m;
        for (int num : nums) 
        {
            ++m[num];
        }
        for (auto a : m) 
        {
            if (k == 0 && a.second > 1) 
            {
                ++res;
            }
            if (k > 0 && m.count(a.first + k))
            {
                ++res;
            }
        }
        return res;
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6545075.html

posted on 2018-04-22 21:54  lina2014  阅读(118)  评论(0编辑  收藏  举报

导航