码迷,mamicode.com
首页 > 其他好文 > 详细

532. K-diff Pairs in an Array

时间:2017-05-31 10:21:51      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:pair   complex   this   ==   map   back   for   sim   https   

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

This is a very simple question. With two-pointer method, the time complexity is O(nlogn), because you need to sort it first. With a hashmap, you could save the time to rearrange it and hence it is only O(n). 

The key points of the question are the boundary conditions. I forgot to consider the cases where k = 0 and k < 0!

Codes with a hashmap:

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        if (nums.empty() || k < 0) return 0;
        int result = 0;
        unordered_map<int, int> set;
        for (int i: nums) {
            set[i]++;
        }
        if (k == 0) {
            for (auto i: set) {
                if (i.second > 1) result++;
            }
        }
        else {
            for (auto i: set) {
                if (set.count(i.first + k)) result++;
            }
        }
        return result;
    }
};

 

532. K-diff Pairs in an Array

标签:pair   complex   this   ==   map   back   for   sim   https   

原文地址:http://www.cnblogs.com/tekkaman-blade/p/6922404.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!