티스토리 뷰
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 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- HashMap
- 프로그래머스 알고리즘
- easy javascript algorithm
- math.max
- Object type casting
- substring()
- 프로그래머스 알고리즘문제
- Collection Framework
- hackerrank javascript solution
- hackerrank javascript
- easy algorithm
- HackerRank Algorithm
- string class in java
- compareTo()
- equals()
- spring boot application
- rest parameter
- code refactoring
- algorithm
- ... in Javascript
- C++
- 프로그래머스
- java
- hackerrank solution
- hackerrank
- Javascript Algorithm
- math.abs
- javascript
- repeat()
- 알고리즘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함