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 | 31 |
Tags
- 가챠
- 눈알빠지겠네
- 코테
- 바질토마토뭐시기
- 유루건
- 코딩테스트
- 발더스모드
- DIY
- 제프딕슨
- 메탈퍼즐
- 롱라이플
- 밥무하마드
- 노노그램
- LeetCode
- 우리시대의역설
- javascript
- 30mf
- 지리데칼
- 프라모델
- 지쿠악스
- 취미
- 블라인드박스
- 누룽지소금빵
- 건담
- 맛집
- 미앤아이
- 건담헤드
- 게임
- 포켓몬
- 발더스게이트
Archives
- Today
- Total
.Zzumbong
[leetCode/JS] 1. 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.
입출력 예
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints
- 2 <= nums.length <= \(10^4\)
- 1 <= s.length <= \(10^4\)
- \(10^9\) <= nums[i] <= \(10^9\)
- \(10^9\) <= target <= \(10^9\) Only one valid answer exists.
내 솔루션
- 순간적으로 어짜피 O(n^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 && nums[i] + nums[j] === target){
return [i, j];
}
}
}
};
최고의 솔루션
- O(n) 솔루션이 있길래 매우 감탄!
- target - nums[i] 를 찾는게 목표라는 점을 간과 했다.
var twoSum = function(nums, target) {
let hash = {};
for(let i = 0; i < nums.length; i++) {
const n = nums[i];
if(hash[target - n] !== undefined) {
return [hash[target - n], i];
}
hash[n] = i;
}
}
감상평
- 똑똑이는 세상에 많다. 많이 푸는 수 밖에 없어 보인다.
'coding test > leetCode' 카테고리의 다른 글
| [leetCode/JS] 222. Count Complete Tree Nodes (0) | 2022.11.23 |
|---|---|
| [leetCode/JS] 2. Add Two Numbers (1) | 2022.11.23 |
| [leetCode/JS] 151. Reverse Words in a String (1) | 2022.11.22 |
| [leetCode/JS] 295. Find Median from Data Stream (0) | 2022.11.22 |
| [leetCode/JS] 901. Online Stock Span (0) | 2022.11.22 |
Comments