본문 바로가기

프로그램 강좌

[LeetCode] 1: TwoSum - javascript

난 가장 일반적으로 풀었다.
되도록이면 더 깔끔한 코드, 더 짧은 런타임이 좋다는건 알지만 지금은 우선 많이 푸는게 좋다고 생각한다.

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

영어로 되어 있어서 당황스러울수도 있지만, 인풋값/결과값을 비교해보면 규칙을 알 수 있다.
nums라는 배열에서 임의로 2개 숫자를 더했을때 합이 target과 일치할때의 숫자 위치값을 output으로 뽑으면 된다. 순서는 0부터 4자리니까 3까지이다.

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let len = nums.length;

    for(let i=0;i<len-1;i++){
        for(let j=i+1;j<len;j++){
            //console.log(i, j);
            if(nums[i]+nums[j]===target) return [i, j];
        }
    }
};

난 이렇게 풀었다.

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

 

Two Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

728x90

'프로그램 강좌' 카테고리의 다른 글

[LeetCode] 13. Roman to Integer - javascript  (0) 2021.11.19
[LeetCode]9. Palindrome Number - javascript  (0) 2021.11.18
CSS 지원 브라우저 확인  (0) 2021.09.27
[CSS]:not  (0) 2021.07.04
[git]SSL certificate problem  (0) 2021.07.02