반응형
지난번에 Two-Sum을 BruteForce 방식으로 풀고 나서 시간을 단축하기 위해 HashMap을 쓰고 싶다 라는 생각을 했었다.
오늘 코드 리뷰 이전까지 바쁘다는 핑계로 시도를 못했지만
오늘 다른 스터디원들의 친절하고 자세한 코드 리뷰를 듣고 용기를 내어 다시 풀어봐야겠다고 생각이 들어 작성을 해보았다.
(Thank you 코틀린 고수 겸쓰, 파이썬 고수 조셉)
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> keyToValue = new HashMap<Integer, Integer>();
int numsLength = nums.length;
int [] result = new int[2];
for(int i = 0; i < numsLength; i++){
int remain = target - nums[i];
if(keyToValue.containsKey(remain)){
result[0] = keyToValue.get(remain);
result[1] = i;
return result;
}
keyToValue.put(nums[i], i);
}
return null;
}
}
결과는!
Runtime : 148ms -> 2ms
Memory : 41.9MB -> 42.8MB
실행 시간이 매우 단축됨!!!
for문 한방에 끝내버리다니 너무 경이롭다 😳
반응형
'ETC > Algorithm' 카테고리의 다른 글
[LeetCode] 53. Maximum Subarray (0) | 2021.12.30 |
---|---|
[LeetCode] 238. Product of Array Except Self (0) | 2021.12.14 |
[Leetcode] Contains Duplicate (1) | 2021.12.09 |
[LeetCode] Add Two Numbers (못풀었다) (0) | 2021.11.30 |
[LeetCode] problem 1. Two Sum (0) | 2021.11.23 |