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.
Loop solution
#include <iostream>
#include <vector>
using namespace std;
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++){
int sum = nums[i] + nums[j];
if(sum == target)
return {i,j};
}
}
return {};
}
int main() {
vector<int> nums = {2,7,15,46};
int target = 9;
auto output = twoSum(nums,target);
for(int out : output)
cout << out << " ";
}Hash map solution
Hash maps are a way to reduce the time complexity of the problem from to .
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
if (hash.count(target - nums[i])) {
return {i, hash[target - nums[i]]};
}
hash[nums[i]] = i;
}
return {};
}
};