문제: https://leetcode.com/problems/two-sum/
Two Sum - LeetCode
Can you solve this real interview question? Two Sum - 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
leetcode.com
1. 코드
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int[] answer = new int[2];
int diff;
for(int i = 0; i < nums.length; i++) {
diff = target - nums[i];
if(map.containsKey(diff)) {
answer[0] = map.get(diff);
answer[1] = i;
break;
}
map.put(nums[i], i);
}
return answer;
}
}
2. 설명
HashMap을 이용하여 target - nums[i] 값이 있다면 해당 값의 인덱스와 i의 값을 answer에 저장하고 answer 반환 후 종료합니다. 만약 존재하지 않으면 map에 해당 값을 저장하고 계속해서 진행합니다.
'컴퓨터 > LeetCode' 카테고리의 다른 글
LeetCode 42 Trapping Rain Water Hard [Java] (0) | 2024.01.01 |
---|---|
LeetCode 5 Longest Palindromic Substring Medium [Java] (0) | 2023.12.30 |
LeetCode 49 Group Anagrams Medium [Java] (0) | 2023.12.29 |
LeetCode 819 Most Common Word Easy [Java] (0) | 2023.12.28 |
LeetCode 937 Reorder Data in Log File Medium [Java] (0) | 2023.12.27 |