
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.
정수 배열 nums와 target을 입력받고,
nums의 요소 둘을 더한 값이 target과 같을 경우, 해당 요소들의 인덱스를 반환하는 문제이다.
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 <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n^2) time complexity
JS로 이런 문제를 풀어보는 게 처음이라, Node.js 환경에서 사용자 입력을 어떻게 받아야 하는지부터 찾아봤다.
터미널에서 입력을 받기 위해, readline 모듈을 사용한다.
const readline = require("readline");
으로 모듈을 불러와서, readline이라는 변수에 저장해준다.
다음으로 readline 인터페이스 설정을 해준다.
createInterface 메서드를 사용해서 rl이라는 인터페이스를 생성했다.
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
input과 output을 설정해서, 사용자와 상호작용한다.
사용자와 프로그램 간의 입출력 처리 방법을 정의한다는 것이다.
process.stdin과 process.stdout은 표준 입출력 스트립을 나타내는데, 각각 사용자가 터미널에서 입력하는 데이터를 받고, 프로그램이 결과를 사용자에게 보여주는 경로를 의미한다.
rl.question("nums = ", (input) => {
rl.question("target = ", (targetInput) => {
const target = parseInt(targetInput);
const nums = input.split(','.map(num=>parseInt(num.trim())));
const result = twoSum(nums,target);
console.log("Output : ", result);
})
})
nums를 input 변수로 입력받고, target을 targetInput변수로 입력받았다.
사용자에게 두 개의 입력을 순차적으로 요청하기 위해서, 두 입력문을 중첩했다.
입력문을 중첩시키면, 첫번째 질문에 대한 응답이 완료되어야 두 번째 질문을 하게 된다.
입력받은 nums를 split(,)을 사용해서 쉼표로 구분하고, map과 parseInt를 사용해 새로운 정수 배열을 만들도록 했다.
(trim은 문자열 앞뒤의 공백을 제거하기 위해 사용했다.)
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let 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];
}
}
}
return [];
}
rl.question("nums = ", (input) => {
rl.question("target = ", (targetInput) => {
const target = parseInt(targetInput);
const nums = input.split(','.map(num=>parseInt(num.trim())));
const result = twoSum(nums,target);
console.log("Output : ", result);
})
})
너무 멋있어요!😋