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.
dic = dict()
for nums 배열의 처음부터 끝까지:
if target - nums[i]가 dic에 있다면:
return (dic[target - nums[i]], i)
dic에 (현재 요소 값: 현재 요소의 인덱스) 저장
return ()
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>(); // number: index
for(int i = 0; i < n; i++) {
if (map.containsKey(target - nums[i])) {
return new int[] {map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[] {};
}
}
처음 생각한 풀이는 브루트 포스로 for문 두개를 돌면서 target과 일치하는 두개의 값을 찾는 방법이었다. 시간복잡도는 O(n^2)이며 44ms 소요되었다.
target - x = y를 보면서 O(n)의 풀이방법을 떠올렸다. 나머지 하나의 수가 map에 있다면 target을 만들 수 있다는 것이기 때문이다.