給你一個(gè)整數(shù)數(shù)組 nums 和一個(gè)整數(shù) k,請(qǐng)你在數(shù)組中找出 不同的 k-diff 數(shù)對(duì),并返回不同的 k-diff 數(shù)對(duì) 的數(shù)目。
k-diff 數(shù)對(duì)定義為一個(gè)整數(shù)對(duì) (nums[i], nums[j]) ,并滿足下述全部條件:
0 <= i, j < nums.length
i != j
nums[i] - nums[j] == k
注意,|val| 表示 val 的絕對(duì)值。
示例 1:
輸入:nums = [3, 1, 4, 1, 5], k = 2
輸出:2
解釋:數(shù)組中有兩個(gè) 2-diff 數(shù)對(duì), (1, 3) 和 (3, 5)。
盡管數(shù)組中有兩個(gè) 1 ,但我們只應(yīng)返回不同的數(shù)對(duì)的數(shù)量。
示例 2:
輸入:nums = [1, 2, 3, 4, 5], k = 1
輸出:4
解釋:數(shù)組中有四個(gè) 1-diff 數(shù)對(duì), (1, 2), (2, 3), (3, 4) 和 (4, 5) 。
示例 3:
輸入:nums = [1, 3, 1, 5, 4], k = 0
輸出:1
解釋:數(shù)組中只有一個(gè) 0-diff 數(shù)對(duì),(1, 1) 。
提示:
- 1 <= nums.length <= 104
- -107 <= nums[i] <= 107
- 0 <= k <= 10
自己的寫法
class Solution {
public int findPairs(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length, ans = 0;
for (int i = 0; i < n; i++) {
boolean flag = false;
// 相同的直接跳過(guò)
while (i + 1 < n && nums[i] == nums[i + 1]) {
i++;
flag = true;
}
// 如果k = 0,相同的數(shù), ans++
if (flag && k == 0) {
ans++;
}
for (int j = i + 1; j < n; j++) {
while (j + 1 < n && nums[j] == nums[j + 1]) {
j++;
}
if (nums[j] - nums[i] == k) {
ans++;
}
}
}
return ans;
}
}
哈希

image.png
public int findPairs(int[] nums, int k) {
Set<Integer> visited = new HashSet<>();
Set<Integer> res = new HashSet<>();
for (int num : nums) {
if (visited.contains(num - k)) {
res.add(num - k);
}
if (visited.contains(num + k)) {
res.add(num);
}
visited.add(num);
}
return res.size();
}
排序 + 雙指針

image.png
class Solution {
public int findPairs(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length, y = 0, res = 0;
for (int x = 0; x < n; x++) {
if (x == 0 || nums[x] != nums[x - 1]) {
while (y < n && (nums[y] < nums[x] + k || y <= x)) {
y++;
}
if (y < n && nums[y] == nums[x] + k) {
res++;
}
}
}
return res;
}
}
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/k-diff-pairs-in-an-array
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。