题目:
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.
Example 1:
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.
Example 2:
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).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
- The pairs (i, j) and (j, i) count as the same pair.
- The length of the array won't exceed 10,000.
- All the integers in the given input belong to the range: [-1e7, 1e7].
翻译:
给定一个整数数组和一个整数k,您需要找到数组中唯一的k-diff对数。 这里,k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是k。
示例1:
输入:[3,1,4,1,5],k = 2
输出:2
说明:阵列中有两个2-diff对,(1,3)和(3,5)。
虽然我们在输入中有两个1,但我们应该只返回唯一对的数量。
示例2:
输入:[1,2,3,4,5],k = 1
输出:4
说明:阵列中有四个1-diff对,(1,2),(2,3),(3,4)和(4,5)。
示例3:
输入:[1,3,1,5,4],k = 0
输出:1
说明:阵列中有一个0-diff对,(1,1)。
注意:
对(i,j)和(j,i)计数为同一对。
阵列的长度不会超过10,000。
给定输入中的所有整数属于范围:[-1e7,1e7]。
示例1:
输入:[3,1,4,1,5],k = 2
输出:2
说明:阵列中有两个2-diff对,(1,3)和(3,5)。
虽然我们在输入中有两个1,但我们应该只返回唯一对的数量。
示例2:
输入:[1,2,3,4,5],k = 1
输出:4
说明:阵列中有四个1-diff对,(1,2),(2,3),(3,4)和(4,5)。
示例3:
输入:[1,3,1,5,4],k = 0
输出:1
说明:阵列中有一个0-diff对,(1,1)。
注意:
对(i,j)和(j,i)计数为同一对。
阵列的长度不会超过10,000。
给定输入中的所有整数属于范围:[-1e7,1e7]。
解题代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
int binarySearch(int target,int begin,int end, vector<int> &nums) {
while(begin <= end) {
int middle = (begin + end)/2;
if(nums[middle] == target) return 1;
else if(nums[middle]<target) begin = middle+1;
else end = middle-1;
}
return 0;
}
public:
int findPairs(vector<int>& nums, int k) {
sort(nums.begin(),nums.end(),less<int>());
int sum = 0;
for(int i = 0; i< nums.size(); i++) {
if(i==0 || i!=0&&nums[i-1]!=nums[i]) sum += binarySearch(nums[i]+k,i+1,nums.size()-1,nums);
}
return sum;
}
};
int main() {
int a[] = {3, 1, 4, 1, 5};
vector<int> v(a,a+5);
Solution s;
cout << s.findPairs(v,2) <<endl;
}
题目状态: