[LeetCode] Two Sum

1. Two Sum

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.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> table;
for(int i = 0; i < nums.size(); i++) {
if(table.count(target - nums[i])) return {i, table[target - nums[i]]};
table[nums[i]] = i;
}
return {};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/two-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.