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]
Output: 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:
1.처음에는 브루트 포스로 풀었다. runtime : 84ms, memory : 39.3MB
const twoSum = function(nums, target) {
let output = [];
for(let i = 0; i < nums.length-1; i++){
for(let j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] === target){
output.push(i);
output.push(j);
}
}
}
return output;
};
브루트 포스로 풀고나서 다른사람들의 답을 보다가 해쉬로도 풀 수 있다는 것을 알게되었다. Runtime : 84ms, memory : 41.8ms
const twoSum = function(nums, target) {
let obj = {};
for(let i = 0; i < nums.length; i++){
obj[nums[i]] = i;
}
for(let i = 0; i < nums.length; i++){
if(Object.keys(obj).includes((target - nums[i]).toString()) && obj[target - nums[i]] !== i){
return [i, obj[target - nums[i]]];
}
}
};
이중 반복문이 돌지 않기 때문에 런타임이나 메모리가 더 줄어들 줄 알았는데 테스트 케이스가 적어서 그런지(?)비슷하거나 오히려 더 나왔다.
위의 해쉬에서는 반복문을 두번 사용한다.
마지막으로 엄청 깔끔하게 풀어놓은 방법을 보고 따라해봤다.
const twoSum = function(nums, target) {
for(let i = 0; i < nums.length; i++){
let copyArr = [...nums];
let subt = target - nums[i];
copyArr[i] = null; //중복(?)을 방지해준다. 예를 들어 nums=[1,2,3,4]이고 target = 6일 때 정답이 [3,3]이런식으로 나오는 걸 방지해준다.
let second = copyArr.indexOf(subt);
if(second > -1){
return [i, second];
}
}
};
갈길이 멀다. 정진하자