Two Sum
2024. 9. 24. 16:13ㆍ알고리즘/Leetcode
반응형
Solution
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

Explanation
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
return new int[]{map.get(nums[i]), i};
}
map.put(target - nums[i], i);
}
return new int[]{};
}
}
First, initialize HashMap to store complements(target - each element in nums) as keys and indexes as values.
Using a for loop, iterate through the nums array and for each element, check whether the complement(target - elements) already exists in map. If it is already stored in the map, return the indexes which add up to target. Otherwise the complement is stored in the map.
반응형
'알고리즘 > Leetcode' 카테고리의 다른 글
| Reverse String (0) | 2024.10.06 |
|---|---|
| Valid Sudoku (2) | 2024.10.04 |
| Move Zeroes (2) | 2024.09.23 |
| Plus One (2) | 2024.09.20 |
| Intersection of Two Arrays II (1) | 2024.09.12 |