Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- 자바스크립트
- 방통대
- boj
- 컴퓨터과학과
- java
- 리트코드
- 코테
- 완전탐색
- 탐욕알고리즘
- greedy
- two pointers
- Binary Search
- LeetCode
- DP
- dynamic programming
- 방송통신대학교
- it
- 깃
- Git
- 자바
- 백준
- 방송대
- 이진탐색
- algorithm
- sliding window
- 그리디
- 코딩
- 알고리즘
- 투포인터
- javascript
Archives
- Today
- Total
개발이 취미인 주니어 기획자
[해쉬맵][JavaScript][LeetCode] #1. Two Sum 본문
728x90
반응형
Two Sum - LeetCode
Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not
leetcode.com
#해쉬맵 #EASY
🌷 문제 설명
✏️ LeetCode 연습문제: Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
🎃 제한 사항
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Only one valid answer exists.
입출력 예
| nums | target | result |
| [2, 7, 11, 15] | 9 | [0, 1] |
| [3, 2, 4] | 6 | [1, 2] |
| [3, 3] |
6 | [0, 1] |
🌷 내 코드
1. 해쉬맵 사용

var twoSum = function(nums, target) {
let map = new Map()
for (let i=0; i< nums.length; i++) {
if (map.has(target-nums[i])) { // 더했을 때 타겟이 되는 숫자(즉, 타겟-현재숫자)가 해쉬맵에 있으면
return [i, map.get(target-nums[i])]
}
map.set(nums[i], i) // key: 숫자, value: 인덱스
}
};
2. 2중포문

var twoSum = function(nums, target) {
for (let i=0; i<nums.length; i++) {
for (let j=0; j<nums.length; j++) {
if (i !== j) {
if ((nums[i] + nums[j]) === target) {
return [i, j]
}
}
}
}
};
3. 투포인터

var twoSum = function(nums, target) {
let left = 0;
let right = left+1;
while (left < nums.length) {
if (nums[left] + nums[right] === target) {
return [left, right]
} else if (right === nums.length-1) {
left++
right = left+1
} else {
right++
}
}
};
🌷 코멘트
순서는 투포인터 > 2중포문 > 해쉬맵 순서로 풀었다. 투포인터로 했는데 속도가 너무 느리길래 그냥 휘리릭 이중포문 돌려봤는데,,, 리트코드 문제인지는 모르겠지만 투포인터보다 이중포문이 더 빠른거 충격.. 아무래도 빠르게 정답 내고 싶어가지고 다른 사람들이 푼 걸 보는데, 해쉬테이블로 많이들 풀었더라! 부끄러운 얘기지만 해쉬테이블이 키밸류 있는 자료구조다 정도밖에 몰랐는데, 그 중 해쉬맵 사용하는 것이 속도가 빠르다는걸 구글링을 통해서 알았따 이거에 대해서도 조만간 블로그 글 찔 예정!
상반기 시작해서 자소서 쓰느라 블로그 글이 뜸했다. 아니 알고리즘 풀어야되는데ㅠㅠ 자소서를 안 쓰면 코테를 못 보고 자소서를 쓰자니 공부가 뭔가 덜하고...🤷🏻♀️ 거기다 갑자기 해외에서 한꺼번에 방한하는 친구들,,, 정처기,,, 저질러놓은 피티,,, 골 프,,, 꺅
블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!
~대가리 꽃밭인 디지털 노마드가 꿈이예요~
🧚♀️ Gyumin Lee
📧 gyumin.q.lee@gmail.com
qminlee723 - Overview
noob. qminlee723 has 8 repositories available. Follow their code on GitHub.
github.com
728x90
반응형
'문제 풀이 > 기본 구현' 카테고리의 다른 글
| [Sorting][JavaScript][LeetCode] #1491. Average Salary Excluding the Minimum and Maximum Salary (0) | 2023.05.02 |
|---|---|
| [해시맵][JavaScript][LeetCode] #13. Roman to Integer (0) | 2023.04.20 |
| [Javascript][프로그래머스] 숫자 짝꿍 자바스크립트 (0) | 2023.03.05 |
| [Javascript][프로그래머스] 카드뭉치 자바스크립트 (0) | 2023.02.17 |