혼자서 해결할 수 있을 때까지 LeetCode 솔루션 공부 3일차: 문제#1.Two-Sum(Easy/JavaScript)
나는 어떤 문제(심지어 쉬운 문제라도)를 해결하는 방법에 대한 단서가 없기 때문에 시간을 낭비하고 알아낼 수 없다고 생각했습니다. 내 접근 방식은 다음과 같습니다.
망각 곡선 퇴치: 앞으로 3일 동안 질문을 다시 하십시오. 그리고 정기적으로 돌아와서 문제를 다시 살펴보세요.
문제 #1. 투썸
Difficulty: Easy
Language: JavaScript
정수 배열
nums
과 정수target
가 주어지면 두 숫자의 인덱스를 반환하여 합이 target
가 되도록 합니다.각 입력에 정확히 하나의 솔루션이 있다고 가정하고 동일한 요소를 두 번 사용하지 않을 수 있습니다.
어떤 순서로든 답변을 반환할 수 있습니다.
예 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
예 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
예 3:
Input: nums = [3,3], target = 6
Output: [0,1]
제약:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
후속 조치: O(n2) 시간 복잡도보다 작은 알고리즘을 생각해낼 수 있습니까?
설명이 포함된 솔루션 1(중첩 루프):
var twoSum = function(nums, target) {
for (i = 0; i < nums.length; i++) {
/*Loop through nums array (note 1) from position 0*/
for (j = i + 1 ; j < nums.length; j++)
/*Loop through nums array (note 1) from position 1 and add up
every possible pair of numbers until they add up to target number.
*/
if(nums[i] + nums[j] == target)
/*For example, if nums = [2,3,4], the possible pairs would be 2+3,
2+4 (starting from first number 2 add the next numbers). That was
all pairs with the number 2. Then pair 3+4 (starting from second
number 3, add the next numbers).*/
return [i, j]
/*return indices for the pairs found*/
}
};
솔루션 1 제출 세부 정보(2022년 2월 11일 기준)
(아래 데이터는 매일 새로운 제출이 있기 때문에 다를 수 있습니다)
설명이 포함된 솔루션 2(객체):
var twoSum = function(nums, target) {
let hash = {};
/*create a object (note 2) and utilize object's property value and
property key*/
for(let i = 0; i < nums.length; i++) {
/*Loop through "nums" array and find desired value to store in the
"hash" object */
const n = nums[i];
/*create a variable n to represent each number in the "nums"
array*/
if(hash[target - n] !== undefined) {
/*find the complementary pair for "n" in "hash" object*/
return [hash[target - n], i];
/*if found, return index of both the complementary pair and "n".
We can access object properties using a square bracket
object[property]*/
}
hash[n] = i;
/*If complementary pair for "n" is not found in "hash", store n
and its index in "hash".
Example Input: nums = [2,7,5,11]; target = 9. The first "n" is 2
and since "hash" is initially empty, we won't find the
complementary pair(target - n)= 7 in there. Hence, we store it in
"hash" with the index of the number 2, which is 0. And now our
"hash" is { '7', 0 } (Key is'7' and value is 0 in this object).
Then we exam if complementary pair of the second number 7 can be
found in the "hash". Since we just stored 7 in the previous step,
it will be found in this step. Therefore, we return the value that
has key of '7' in the object: hash[target - n]. And the index of
second number '7':[i]. That is [0,1]. And this is the output of
this example*/
}
}
솔루션 2 제출 세부 정보(2022년 2월 12일 기준)
(아래 데이터는 매일 새로운 제출이 있기 때문에 다를 수 있습니다)
**********************************************
참조:
LeetCode Problem Link
LeetCode Discussion
Note 1: For...Loop
Note 2: JavaScript Hash Table
Note 3: For...Loop
Blog Cover Image Credit
Reference
이 문제에 관하여(혼자서 해결할 수 있을 때까지 LeetCode 솔루션 공부 3일차: 문제#1.Two-Sum(Easy/JavaScript)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/killingleetcode/day-3-of-studying-leetcode-solution-until-i-can-solve-one-on-my-own-problem1two-sumeasyjavascript-4o6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)