Table of Contents
ToggleSolution
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map numToIndex;
for (int i = 0; i < nums.size(); ++i) {
if (const auto it = numToIndex.find(target - nums[i]);
it != numToIndex.cend())
return {it->second, i};
numToIndex[nums[i]] = i;
}
throw;
}
};
Explanation
The above code implements a solution to find two numbers in a vector that add up to a specific target value. It uses an unordered map to store the numbers and their indices, and a loop to iterate through the vector and perform the necessary calculations. If a solution is found, the function returns the indices of the two numbers. Otherwise, an exception is thrown.
class Solution {
public int[] twoSum(int[] nums, int target) {
Map numToIndex = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (numToIndex.containsKey(target - nums[i]))
return new int[] {numToIndex.get(target - nums[i]), i};
numToIndex.put(nums[i], i);
}
throw new IllegalArgumentException();
}
}
Explanation
The code implements a solution to find two numbers in an array that add up to a given target value. It utilizes a map to store numbers and their indices for efficient lookup. If a solution is found, it returns the indices of the two numbers; otherwise, it throws an exception to indicate that no solution is possible.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numToIndex = {}
for i, num in enumerate(nums):
if target - num in numToIndex:
return numToIndex[target - num], i
numToIndex[num] = i
Explanation
The code represents a solution for finding two numbers in a list that add up to a target value. It utilizes a dictionary to store the numbers and their corresponding indices as key-value pairs. By iterating through the list and checking for the complement of each number, the code efficiently solves the “Two Sum” problem.