Created
August 8, 2020 00:46
-
-
Save germanescobar/607ac9d398db8cfc7344c7c5c1baf91b to your computer and use it in GitHub Desktop.
This file contains 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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.