package array.iterative;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement))
return new int[] { map.get(complement), i };
map.put(nums[i], i);
}
return new int[] { -1, -1 };
}
}
class TwoSum:
def twoSum(self, nums: list[int], target: int) -> list[int]:
index_by_value: dict[int, int] = {}
for index, value in enumerate(nums):
complement = target - value
match_index = index_by_value.get(complement)
if match_index is not None:
return [match_index, index]
index_by_value[value] = index
return [-1, -1]
#include <unordered_map>
#include <vector>
class TwoSum {
public:
std::vector<int> twoSum(const std::vector<int>& nums, const int target) const {
std::unordered_map<int, int> index_by_value;
index_by_value.reserve(nums.size());
const auto size = static_cast<int>(nums.size());
for (int index = 0; index < size; ++index) {
const int value = nums[index];
const int complement = target - value;
const auto match = index_by_value.find(complement);
if (match != index_by_value.end())
return {match->second, index};
index_by_value[value] = index;
}
return {-1, -1};
}
};