Content
Two Sum solution on Leet Code
The simple solution
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); ++i) { for (int j = i + 1; j < nums.size(); ++j) { if (nums.at(i) + nums.at(j) == target) { return {i,j}; } } } return {}; } };
Solution using map
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int n = nums.size(); std::map<int, int> targets; for (int i = 0; i < n; ++i) { if (targets.count(nums[i]) && targets[nums[i]] != i) { return {targets[nums[i]], i}; } targets[target - nums[i]] = i; } return {}; } };