twoSum
함수에 숫자배열과 '특정 수'를 인자로 넘기면,
더해서 '특정 수'가 나오는 index를 배열에 담아 return해 주세요.
nums: 숫자 배열
target: 두 수를 더해서 나올 수 있는 합계
return: 두 수의 index를 가진 숫자 배열
예를 들어,
nums은 [4, 9, 11, 14]
target은 13
nums[0] + nums[1] = 4 + 9 = 13 이죠?
그러면 [0, 1]이 return 되어야 합니다.
# 가정
target으로 보내는 합계의 조합은 배열 전체 중에 2개 밖에 없다고 가정하겠습니다.
const twoSum = (nums, target) => {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
twoSum([4, 9, 11, 14], 13);
👉🏻 2중 For문으로 돌리면서 해당하는 값과 일치하는 수 반환
const twoSum = (nums, target) => {
const combination = [];
const result = [];
// 두 수가 뽑혀지는 경우의 수를 모두 계산
for(let i = 0; i < nums.length; i++) {
for(let j = i; j < nums.length; j++) {
combination.push([nums[i], nums[j]]);
}
}
// reduce/map 메서드를 통한 합산값 출력 후 target과 비교 하여 결과 배열에
for(let i = 0; i < combination.length; i++) {
let sumComp = combination[i].reduce((a, b) => a + b)
if(sumComp === target) {
result.push(source.indexOf(combination[i][0]));
result.push(source.indexOf(combination[i][1]));
return result;
}
}
}
👉🏻 간단하게 풀 수 있는 문제를 한 번 더 거쳐간 느낌
👉🏻 모든 문제를 쪼개기 전에 있어서 한 번 더 생각을 해보고 진행을 해야할듯
👉🏻 Array method에 대한 정립 필요(map, filter, reduce, sort 등)