[LeetCode] 1. Two Sum

1. Two Sum

문제

숫자로 이루어진 배열과, 숫자로된 타겟을 입력받아서 배열에서 타켓을 만들 수 있는 숫자의 인덱스를 반환.

만약에 배열 [1, 3, 6, 7]과 타겟 8을 입력 받는다면 [0, 3]를 반환한다


1
2
3
4
5
6
7
var twoSum = function(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        const test = target - nums[i];
        const index = nums.indexOf(test);
        if (index != -1 && index !== i) return [i, nums.indexOf(test)];
    }
};

설명

우선, nums에 있는 두 값으로 target을 만들어야 함으로

nums에 있는 A + B = target이라 생각하고 A = target - B로 생각해서

nums에 B가 있는지 확인하고, B가 있다면 그 index로 배열을 만들어서 리턴합니다.


Leetcode

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:

1
2
3
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

1
2
Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

1
2
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(n2) time complexity?

Built with Hugo
Theme Stack designed by Jimmy