Leetcode - K-diff Pairs in an Array (Python)

preview_player
Показать описание
October 2020 Leetcode Challenge
Leetcode - K-diff Pairs in an Array
Рекомендации по теме
Комментарии
Автор

I was mad when I saw Neetcode didn’t have a video for this one but this guy is just as good

Philgob
Автор

it took me a little bit to realize this was similar to two sum. thanks tim!

janmichaelaustria
Автор

Thanks for the vid, I too recognised this as a 2 sum variation but could not come up with a solution, also the k=0 is what makes this s a medium problem and you handled that well so thanks for that.

amandubey
Автор

Thank you very much for your video.
I done with following way. But your solution with count is better than using set
def k_difference(l, k):

c=set()
for i in l:
if k!=0:
if i-k in lookup:
c.add((i, (i+k)))
else:
if k==0 and lookup[i]>1:
c.add((i, i))
return len(c)
print(k_difference([1, 3, 1, 5, 4], 0))

sharifmansuri
Автор

TypeError: 'builtin_function_or_method' object is not iterable
for key, v in c.items:
Line 6 in findPairs (Solution.py)
ret = Solution().findPairs(param_1, param_2)
Line 34 in _driver (Solution.py)
_driver()
Line 45 in <module> (Solution.py)

gauravmehta
Автор

What is the difference between collections.Counter and Counter?

kentsang
Автор

If someone has questions on how key+k is arrived, here is the answer

abs(i-j) = k
Lets take an example:

If k = 8 and i = 3

abs(3-j) = 8
=> j should be 11 here to satisfy the equation
To think in another way, abs(i-j) = j-i
j-i = k
j = i+k (j=3+8)

spicy
Автор

A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:

0 <= i, j < nums.length
i != j
|nums[i] - nums[j]| == k

Example:
arr = [1, 1, 1, 1, 1] and k =0

why is the answer still 1? would it not be 2? according to the constrains above 2 seems correct

lonecreeperbrine
Автор

why my code is wrong
nums.sort()
for i in range(n):
if nums[i]+k in nums and i!=nums.index(nums[i]+k):
c+=1
return c

Srisaiganeshkommineni