Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Created August 8, 2020 00:46
Show Gist options
  • Save germanescobar/607ac9d398db8cfc7344c7c5c1baf91b to your computer and use it in GitHub Desktop.
Save germanescobar/607ac9d398db8cfc7344c7c5c1baf91b to your computer and use it in GitHub Desktop.
var findPairs = function(nums, k) {
if (k < 0) return 0
if (k === 0) {
return handleZeroCase(nums)
} else {
return handleGeneralCase(nums, k)
}
};
function handleZeroCase(nums) {
const repetidos = new Set()
const map = new Map()
let count = 0
for (let i=0; i < nums.length; i++) {
const num = nums[i]
if (map.has(num) && !repetidos.has(num)) {
count++
repetidos.add(num)
} else {
map.set(num, 1)
}
}
return count
}
function handleGeneralCase(nums, k) {
const set = new Set(nums)
let count = 0
set.forEach(function(num) {
set.delete(num)
if (set.has(num + k)) {
count++
}
if (set.has(num - k)) {
count++
}
})
return count
}
@germanescobar
Copy link
Author

Esta solución pasa pero maneja independiente el caso cuando k es 0. Sería interesante buscar una solución O(n) que una los dos casos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment