[Leetcode] Two Sum
아직 한국어 번역이 없습니다. 영문 원문을 표시합니다.
Given an array of integers numsand 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 <= 10``4
-10``9`` <= nums[i] <= 10``9
-10``9`` <= target <= 10``9
Only one valid answer exists.
**Follow-up: **Can you come up with an algorithm that is less than O(n``2``)time complexity?
how to approach?
function twoSum(nums: number[], target: number): number[] {
let subtract = new Map()
for (let i = 0;i<nums.length;i++){
const cur = nums[i]
const x = target - cur
if(subtract.has(x)){
return [i,nums.indexOf(x)]
}
subtract.set(cur,i)
}
};
- create a Map for subtracts from target to number element in nums.
- also check the if subtracted value does exist already in the Map
- if map already has the value then return the index of the current element and index of the subtracted value's index.
- lastly, in for loop, set the key as element and value as index of the element.
summary
this leetcode problem is solved by typescript language.
using map to set element and index in it and check the each element's subtract value in for loop, if it has the value then return the index and index of the subtracted value. since it has exactly one solution.