|
| 1 | +package com.stevesun.solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * 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. |
| 7 | +
|
| 8 | + Example 1: |
| 9 | + Input: [3, 1, 4, 1, 5], k = 2 |
| 10 | + Output: 2 |
| 11 | + Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). |
| 12 | + Although we have two 1s in the input, we should only return the number of unique pairs. |
| 13 | +
|
| 14 | + Example 2: |
| 15 | + Input:[1, 2, 3, 4, 5], k = 1 |
| 16 | + Output: 4 |
| 17 | + Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). |
| 18 | +
|
| 19 | + Example 3: |
| 20 | + Input: [1, 3, 1, 5, 4], k = 0 |
| 21 | + Output: 1 |
| 22 | + Explanation: There is one 0-diff pair in the array, (1, 1). |
| 23 | +
|
| 24 | + Note: |
| 25 | + The pairs (i, j) and (j, i) count as the same pair. |
| 26 | + The length of the array won't exceed 10,000. |
| 27 | + All the integers in the given input belong to the range: [-1e7, 1e7]. |
| 28 | + */ |
| 29 | +public class KdiffPairsinanArray { |
| 30 | + |
| 31 | + //this O(n^2) will result in TLE |
| 32 | + public int findPairs_On2(int[] nums, int k) { |
| 33 | + Set<List<Integer>> pairsSet = new HashSet<>(); |
| 34 | + for (int i = 0; i < nums.length-1; i++) { |
| 35 | + for (int j = i+1; j < nums.length; j++) { |
| 36 | + if (Math.abs(nums[j] - nums[i]) == k) { |
| 37 | + pairsSet.add(nums[i] > nums[j] ? Arrays.asList(nums[j], nums[i]) : Arrays.asList(nums[i], nums[j])); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return pairsSet.size(); |
| 42 | + } |
| 43 | + |
| 44 | + public int findPairs(int[] nums, int k) { |
| 45 | + if (nums == null || nums.length == 0 || k < 0) return 0; |
| 46 | + |
| 47 | + Map<Integer, Integer> map = new HashMap(); |
| 48 | + for (int i : nums) { |
| 49 | + map.put(i, map.getOrDefault(i, 0) + 1); |
| 50 | + } |
| 51 | + |
| 52 | + int answer = 0; |
| 53 | + for (int key : map.keySet()) { |
| 54 | + if (k == 0) { |
| 55 | + if (map.get(key) >= 2) answer++; |
| 56 | + } else { |
| 57 | + if (map.containsKey(key + k)) answer++; |
| 58 | + } |
| 59 | + } |
| 60 | + return answer; |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments