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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
풀이 :
주어진 nums 내부에 2개의 숫자가 target이 되도록 찾는 문제
(1) HashMap을 이용해서 HashMap의 key가 target - num를 갖고 있는지 체크 (num은 for loop를 사용하면서 pointer가 가르키는 현재 위치의 값.)
(2-1) 없다면 HashMap에 key로는 num, value로 현재 index 값을 넣어줌
(2-2) 있다면 return 할 int array를 만든거에 target-num, 현재 index 값을 넣어줌
여기서 HashMap에 있다는 의미는 A+B = target을 -> target - B = A처럼 생각해주고 A 가 HashMap에 있는지를 체크해서 찾은거임
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
if(map.containsKey(target - num)) {
result[0] = map.get(target-num);
result[1] = i;
break;
}
map.put(num, i);
}
return result;
}
}
'코딩테스트 준비 > Leetcode' 카테고리의 다른 글
20. Valid Parentheses (0) | 2022.07.28 |
---|---|
리츠코드 문제. (0) | 2022.07.27 |