티스토리 뷰
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
- Javascript Algorithm
- hackerrank javascript solution
- spring boot application
- java
- compareTo()
- javascript
- hackerrank solution
- string class in java
- repeat()
- Collection Framework
- hackerrank
- 프로그래머스
- substring()
- hackerrank javascript
- Object type casting
- ... in Javascript
- code refactoring
- easy javascript algorithm
- equals()
- easy algorithm
- rest parameter
- algorithm
- HashMap
- 프로그래머스 알고리즘
- math.max
- 프로그래머스 알고리즘문제
- C++
- HackerRank Algorithm
- 알고리즘
- math.abs
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
글 보관함