Patrones de DSA
Preguntas de LeetCode por patrón, una chuleta, una práctica de patrones y ejecuciones paso a paso.
1Two Sum
- Entrada
- nums = [2,7,11,15], target = 9
- Salida
- [0, 1]
| # | Step | i | nums[i] | need | seen |
|---|---|---|---|---|---|
| 1 | 7 not seen, store 2 | 0 | 2 | 7 | {} |
| 2 | 2 is in seen at 0, return | 1 | 7 | 2 | {2: 0} |
Código trazado
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i);
}
}
return twoSum([2, 7, 11, 15], 9);