記錄

[JS] 01. Two Sum 본문

FRONTEND STUDY/LeetCode

[JS] 01. Two Sum

prts 2022. 10. 7. 23:40

문제 링크: https://leetcode.com/problems/two-sum/
난이도: Easy

 

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.

 

정수 숫자의 배열과 정수 목표값이 주어지면 목표값에 더해지도록 두 숫자의 index를 반환합니다.

각 입력에 정확히 하나의 솔루션이 있다고 가정할 수 있으며, 동일한 요소를 두 번 사용할 수 없습니다.

답변은 임의의 순서로 반환할 수 있습니다.

 

 

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. 유효한 답변은 하나만 있습니다.

문제 풀이

 

nums 배열 내 두 정수 합=target 값이 되는 두 정수의 nums 배열 내 index 값을 반환하는 식을 구현한다.

 

 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]
        }
    }
};

 

'FRONTEND STUDY > LeetCode' 카테고리의 다른 글

[JS] 34. Find First and Last Position of Element in Sorted Array  (1) 2022.10.14
[JS] 136. Single Number  (0) 2022.10.12
[JS] 215. Kth Largest Element in an Array  (0) 2022.10.11
[JS] 7. Reverse Integer  (0) 2022.10.08
[JS] 50. Pow(x, n)  (0) 2022.10.08
Comments