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