# [일일코딩 #34] Two sum

이건 쉬웠당 15분도 안걸린듯
몇년전에도 풀었던거같다 유명한 문제자너 이름도 익숙하구

Question

링크

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

My answer

어제도 썼던 indexOf 써서 풀었당
for문을 돌리면서 target에서 el을 뺀 diff값이 나머지 array에 있는지 확인하면 됨.

var twoSum = function(nums, target) {
    for(let i=0; i<nums.length; i++) {
        const foundIdx = nums.indexOf(target - nums[i]);
        if (foundIdx >= 0 && foundIdx !== i) {
            return [i, foundIdx]
        }
    }
};

옛날에 푼걸 봐볼까

걍 똑같이 풀었네..

var twoSum = function(nums, target) {
  for (var i = 0; i <nums.length; i++) {
    var lastIdx = nums.lastIndexOf(target - nums[i]);
    if(lastIdx > 0) return new Array(i, lastIdx);
  }
};

Published by

Yurim Jin

아름다운 웹과 디자인, 장고와 리액트, 그리고 음악과 맥주를 사랑하는 망고장스터

One thought on “# [일일코딩 #34] Two sum”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s