알고리즘
[LeetCode] 1. Two Sum | 자바스크립트
남양주개발자
2022. 8. 31. 00:06
728x90
반응형
문제
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.
해결방법
function twoSum(nums: number[], target: number): number[] {
const vals = {};
for (let i = 0; i < nums.length; i++) {
if (target - nums[i] in vals) {
return [vals[target - nums[i]], i];
} else {
vals[nums[i]] = i;
}
}
return [];
};
728x90
반응형
그리드형