Notice
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- 실전프로젝트
- TS
- ChatGPT
- 알pdf #파일탐색기미리보기안될때
- Expo
- 알고리즘기초주차
- 항해99
- 팀워크최고
- TDD
- 챗GPT
- 프론트엔드
- REACT
- D반8조
- 달리기반
- 웹개발종합반
- 스파르타코딩클럽
- 7기
- 리액트
- 프로그래머스
- Ai
- 코린이
- 멍친구
- rn
- NotionAI
- 맥린이
- 사전준비
- ReactNative
- 필수강의
- typeScript
- Programmers
Archives
- Today
- Total
FrontEnd :-)
[LeetCode-JS] Two Sum 본문
🙋 문제: Two Sum / Easy
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]
🅰️ 풀이:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for (let i=0; i < nums.length; i++){
for (let j= i+1; j < nums.length; j++){
if (nums[i] + nums[j] === target){
return [i, j]
}
}
}
};
>> j를 i+1로 설정하는 게 핵심?!
✅ 다른 사람 풀이:
var twoSum = function(nums, target) {
const hashMap = { }
for (let i = 0; i < nums.length ; i ++) {
let num = nums[i]
if(hashMap[target - num] !== undefined) {
return [i, hashMap[target - num]]
}
hashMap[num]=i
}
};
var twoSum = function(nums, target) {
let obj = {};
for (let i = 0; i < nums.length; i++) {
let find = target-nums[i];
if (nums[i] in obj) {
return [obj[nums[i]], i];
} else {
obj[find] = i;
}
}
};
>> 해시테이블 이용한 방법
'JavaScript > Algorithm' 카테고리의 다른 글
| [LeetCode-JS] Merge Two Sorted Lists (0) | 2022.12.15 |
|---|---|
| [LeetCode-JS] Valid Parentheses (0) | 2022.12.10 |
| [LeetCode-JS] Longest Common Prefix (0) | 2022.12.09 |
| [LeetCode-JS] Roman to Integer (0) | 2022.12.08 |
| [LeetCode-JS] Palindrome Number (0) | 2022.12.07 |
Comments