首页 > 其他 > 详细

532. K-diff Pairs in an Array

时间:2017-05-31 09:35:37      阅读:257      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!