카테고리 없음
[LeetCode/JS] Two Sum
jhlee_
2021. 8. 27. 19:17
문제
https://leetcode.com/problems/two-sum/
문제설명
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에서 2개의 숫자를 더했을 때, 그 값이 target이되는 index를 리턴해라.
각 입력(nums 두개의 수)은 정확한 해답을 갖을수 있으며, 같은 element를 두번 사용할수 없다.
이 문제의 답은 순서대로 리턴해라.
예시
// expample 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]
풀이과정
1. 같은 element를 사용하지 않을 것
2. nums Array 안에 두 수를 더하기
이중 for문을 사용하기로했다. 같은 element를 사용하면 안되므로 1번의 내용을 if문으로 넣어주기로함.
소스코드
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (i !== j) {
if (target === nums[i] + nums[j]) {
return [i, j]
}
}
}
}
};
다른풀이
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을 해줬다면 if ( i !==j )를 쓰지 않아도 됨.
728x90