LeetCode 코딩 문제 2020/12/15 - Two Sum

이호현·2020년 12월 15일
0

Algorithm

목록 보기
34/138

[문제]

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.

(요약) 배열에서 target을 합으로 만들 수 있는 두 숫자의 indexreturn하라.

[풀이]

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

반복문 돌면서 target에서 i번째 숫자를 뺀 숫자가 nums에 포함되어 있으면 iindexreturn.
자기 자신이 또 있으면 안되니까 iindex는 다르다는 조건을 추가.

profile
평생 개발자로 살고싶습니다

0개의 댓글