[LeetCode]1. Two Sum - JavaScript

롱롱·2022년 8월 10일
0

LeetCode 문제풀이

목록 보기
1/5

LeetCode에서 풀어보기

👀 Problem

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]
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.

✔ Solution

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

nums 배열을 돌며 더해서 target과 같아지는 [i, j]를 찾아 출력했다.
찾아보니 이런 방식을 Brute Force라고 하는데, 조합 가능한 모든 문자열을 하나씩 대입해 보는 방식으로 항상 정확도 100%를 보장하나 시간이 오래걸린다는 단점이 존재한다.

다른 사람들의 Solution을 보니 다양한 풀이방법이 있던데 다른 알고리즘들을 더 공부해봐야 할 것 같다.

profile
개발자를 꿈꾸며 공부중입니다.

0개의 댓글