首页 > 代码库 > 532. K-diff Pairs in an Array
532. K-diff Pairs in an Array
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。