nums: 배열target: 정수nums에 들어있는 정수들 중 두 개를 골랐을 때, 두 개의 합이 target이 되는 수를 구하시오.nums[]의 index를 넣어야 함. 일단 지금 당장 생각나는 거
1. nums를 HashMap에 넣는다. -> O(n)
2. nums를 돌면서 HashMap에 target으로 충족되는 게 있는지 확인한다. -> O(n)
=> 시간복잡도 O(n), 공간복잡도 O(n)
(3, 0), (2, 1), (4, 2)
Time complexity:O(n)
Space complexity:O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int[] ans = new int[2];
for (int i=0; i<nums.length; i++){
map.put(nums[i], i);
}
for (int i=0; i<nums.length; i++){
if (map.containsKey(target - nums[i])){
if (i != map.get(target - nums[i])){
ans[0] = i;
ans[1] = map.get(target - nums[i]);
return ans;
}
}
}
return ans;
}
}