거의 알고리즘 일기장

[leetCode] - 1. Two Sum - 본문

알고리즘 문제풀이

[leetCode] - 1. Two Sum -

건우권 2023. 3. 31. 22:04

problem

https://leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - 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

leetcode.com

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.

solve

This problem is so simple and easy.

because, can use brute force!

just compare for equality target , nums[i] + nums[i+1]

code

function twoSum(nums: number[], target: number): number[] {
    let result:number[]|null = null;

    //for loop twice
    for(let i=0; i<nums.length; i++){
        //if result is not null, previous calcurate find result
        if(result){
            break;
        }

        const c1 = nums[i];
        for(let j=i+1; j<nums.length; j++){
            const c2 = nums[j];

            //if c1, c2 is same target, this caclurate done
            if(c1 + c2 === target){
                result = [i, j];
                break;
            }
        }
    }

    return result;
};
반응형
Comments