[Leetcode] two sum (python, javascript)
728x90
반응형
합한 수가 target이면 현재 수 x와 target-x의 위치를 찾으면 된다
각 숫자의 위치를 저장해가면서 이미 지나간 위치에서 target-x가 있다면 [현재위치, dict[target-x]] 를 리턴하면 된다.
1. python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict={}
for i,x in enumerate(nums):
if target-x in dict:
return [dict[target-x],i]
dict[x]=i
2. javascript
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const map={};
for(let i=0;i<nums.length;i++){
const another=target -nums[i];
if(another in map){
return [map[another],i];
}
map[nums[i]]=i;
}
};
728x90
반응형
'Leetcode' 카테고리의 다른 글
leetCode - move zeros (python, javascript) (0) | 2020.12.16 |
---|---|
[Leetcode] 20. valid parentheses (python, easy) (0) | 2020.11.25 |
[LeetCode] 파이썬 알고리즘 인터뷰 리뷰 복습하며 다시 풀기 (2020.11.10) (0) | 2020.11.10 |
[LeetCode] 7.Reverse Integer (문자열 연산) (0) | 2020.11.09 |
[LeetCode] 15. 3sum (python, javascript, two pointer) (0) | 2020.10.31 |
TAGS.