std::vector<int> twoSum(std::vector<int> &nums, int target){ std::unordered_map<int, int> hashMap; // Key: nums的值, Value: 該值在nums中的index auto size = nums.size();
for (int i = 0; i < size; ++i) { hashMap[nums[i]] = i; }
for (int i = 0; i < size; ++i) { int complement = target - nums[i]; if (hashMap.count(complement) <= 0) continue; if (hashMap[complement] == i) continue;
return {i, hashMap[complement]}; }
return {}; }
解法2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
std::vector<int> twoSum(std::vector<int>& nums, int target){ std::unordered_map<int, int> numIndexMap; // Map to store number-index pairs
for (int i = 0; i < nums.size(); ++i) { int complement = target - nums[i]; // Calculate the complement needed to achieve target sum
// Check if the complement exists in the map if (numIndexMap.find(complement) != numIndexMap.end()) { // If found, return the indices of the current number and its complement return {numIndexMap[complement], i}; }
// Add the current number and its index to the map numIndexMap[nums[i]] = i; }
// Return an empty vector if no solution is found return {}; }