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
을 합으로 만들 수 있는 두 숫자의 index
를 return
하라.
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
에 포함되어 있으면i
와index
를return
.
자기 자신이 또 있으면 안되니까i
와index
는 다르다는 조건을 추가.