532. K-diff Pairs in an Array
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 45% Topics: Array, Hash Table, Two Pointers, Binary Search, Sorting
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(n)
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0: return 0
result, lookup = set(), set()
for num in nums:
if num-k in lookup:
result.add(num-k)
if num+k in lookup:
result.add(num)
lookup.add(num)
return len(result)
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions