티스토리 뷰

Algorithms

two sum

seoca 2021. 3. 26. 23:34

 

function twoSum(numArr, target) {
    //Create new Map
    const numMap = new Map();

    //Loop with index
    for (const [index, element] of numArr.entries()) { //array iterator that returns key/value for each index.
        //need to calculate the difference so we can compare with array elements
        const diff = target - element

        //If our numMap can find the current element which matches the diff, return the array
        if (numMap.has(diff)) { //returns a boolean indicating whether an element with the specified key exists or not
            return [numMap.get(diff), index] //
        }

        //Else add the diff of that element to numMap.
        numMap.set(element, index) // lets you store unique values of any type
    }
}

console.log(twoSum([6, 2, 3, 9, -5, 5, 7, 2], 9))

'Algorithms' 카테고리의 다른 글

Using array.reduce method to count duplicate elements  (0) 2022.10.23
find intersection algorithm  (0) 2021.03.28
on sale products algorithm  (0) 2021.02.12
How many typos in a string  (0) 2021.02.12
CamelCase  (0) 2021.02.12