Problem:
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.
Answer:
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(nums.size() < 2)
return 0;
//之前用map比较耗时
/*map<int, int> mp;
for(auto i : nums){
if(mp.find(i) == mp.end()){
mp.insert(make_pair(i,1));
}
else{
++mp.find(i)->second;
}
}*/
int count = 0;
vector<int> temp = nums;
sort(temp.begin(), temp.end());
if(k < 0)
return 0;
if(k==0) {
for(int i=0;i<temp.size()-1;i++)
//若数组下标为0且与下标为1的相等或者下标为i与i+1相等但i和i-1不等(避免重复计数eg:1,1,1)
if(temp[i]==temp[i+1]&&(i==0||temp[i]!=temp[i-1])){
++count;
}
return count;
}
/*for(auto beg = mp.begin(); beg != mp.end(); ++beg){
temp.push_back(beg->first);
}*/
for(int i = 0; i < temp.size()-1; ++i){
if(temp[i] != temp[i+1]){
//binary_search:binary_search(data, data + N, key);查找范围:从data数组的第一个元素到第N-1个元素;如果找到key,返回true;没有找到,返回false.常用于查找元素是否存在.
if(binary_search(temp.begin(), temp.end(), temp[i]+k))
++count;
}
}
return count;
}
};