[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
반응형
그리드형
'알고리즘' 카테고리의 다른 글
[LeetCode] 20. Valid Parentheses | 자바스크립트 (0) | 2022.09.10 |
---|---|
[LeetCode] 14. Longest Common Prefix | 자바스크립트 (0) | 2022.09.08 |
[LeetCode] 13. Roman to Integer | 자바스크립트 (0) | 2022.09.05 |
자바스크립트 문자열 내림차순 정렬하는 방법 (Sorting strings in descending order in Javascript) (0) | 2021.08.10 |