FrontEnd :-)

[LeetCode-JS] Two Sum 본문

JavaScript/Algorithm

[LeetCode-JS] Two Sum

code10 2022. 12. 5. 18:31

🙋 문제: 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.

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]


🅰️ 풀이:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
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로 설정하는 게 핵심?!


✅ 다른 사람 풀이:

var twoSum = function(nums, target) {
    
    const hashMap = { }
    for (let i = 0; i < nums.length ; i ++) {
       let num = nums[i]
       if(hashMap[target - num]  !== undefined) {
           return [i, hashMap[target - num]]
       }
        hashMap[num]=i
    }
};
 var twoSum = function(nums, target) {
 	let obj = {};
        for (let i = 0; i < nums.length; i++) {
            let find = target-nums[i];
            if (nums[i] in obj) {
                return [obj[nums[i]], i];
            } else {
                obj[find] = i;
            }
        }
};

>> 해시테이블 이용한 방법

'JavaScript > Algorithm' 카테고리의 다른 글

[LeetCode-JS] Merge Two Sorted Lists  (0) 2022.12.15
[LeetCode-JS] Valid Parentheses  (0) 2022.12.10
[LeetCode-JS] Longest Common Prefix  (0) 2022.12.09
[LeetCode-JS] Roman to Integer  (0) 2022.12.08
[LeetCode-JS] Palindrome Number  (0) 2022.12.07
Comments