532. K-diff Pairs in an Array
一、问题描述
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
二、输入输出
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
三、解题思路
- 注意是绝对距离,是
|i - j|
所以k < 0
直接返回0。不要丢掉这种情况 - 假设k!=0 那么可以把数存到set中,set是集合,里面的元素不会重复。依次遍历,并查看
set(i) + k
是否也在set中:在,计数器加1;不在,继续遍历 - 对于
k=0
,同样借助set。在插入到set之前,首先判断是否已经包含该数字,如果有,说明出现了相同的数字,计数器加一。 - 注意
k=0
时,<1,1>
这是1种,如果输入是[1,1,1,1,1]
那么应该输出是1,不是4。所以我们需要把出现过的相同的数记下来,遍历过程中如果再次出现,直接忽略,不在考虑
int findPairs(vector<int>& nums, int k) {
set<int> s;
int n = nums.size(), ret = 0;
if( k < 0 ){
return 0;
}
else if( k == 0){
set<int> searched;
for (int i = 0; i < n; ++i) {
if (s.find(nums[i]) != s.end() && searched.count(nums[i]) == 0) {
ret++;
searched.insert(nums[i]);
}
else
s.insert(nums[i]);
}
}else{
for (int i = 0; i < n; ++i) {
s.insert(nums[i]);
}
for (set<int>::iterator ite = s.begin(); ite != s.end(); ite++){
if(s.find(*ite + k) != s.end())
ret++;
}
}
return ret;
}