題目

TwoSum(Easy)

解法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 {};
}

說明

最簡單暴力的做法是用2個for loop計算,但這樣時間複雜度就會是O(n²),如果想減少成O(n)可以使用hashmap利用他快速查找的特性來實現。

std::unordered_map

  • count(): 檢查此map中是否有傳入的元素, 如果有則回傳1, 沒有則回傳0
  • find(): 檢查此map中是否有傳入的元素, 如果有則回傳指向該元素的迭代器, 沒有則回傳指向end()的迭代器

__END__