Description
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.
1 | Example 1: |
1 | Example 2: |
1 | Example 3: |
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].
Method
题目中给的是无序的数组然后需要求差值。我们可以先把无序数组进行排序将其变成有序,然后从第一个数开始遍历,通过两个pointer来比较两个数之间的差值。这里要注意的是重复的数字只计算一次,排序之后重复的数字合并到了一起,我们只需要判定第一个pointer前面的数字是否和pointer指向的数字的值相等,若相等则跳过。
Solution
1 | public class Solution { |