Created
September 4, 2017 20:56
-
-
Save cixuuz/96e6d3869a3316539c8c8bb7956794ea to your computer and use it in GitHub Desktop.
[532. K-diff Pairs in an Array] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
// O(n) O(n) | |
public int findPairs(int[] nums, int k) { | |
if (nums.length < 2 || k < 0) return 0; | |
HashSet visited = new HashSet(); | |
HashSet pairs = new HashSet(); | |
for (int n : nums) { | |
if (visited.contains(n+k)) { | |
pairs.add(n+k < n ? n+k : n); | |
} | |
if (visited.contains(n-k)) { | |
pairs.add(n-k < n ? n-k : n); | |
} | |
visited.add(n); | |
} | |
return pairs.size(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment