Problem Statement
Given an integer array of size N, return indices of the two numbers such that they add up to a specific target.
Function Signature:
C++
vector<int> twoSum(vector<int> input, int target) {...}
Inputs:
input = [2, 4, 6, 7]
target = 9,
Outputs:
[0, 3]
(because input[0] + input[3] = 2 + 7 = 9)
Solution: Hash Table
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++) {
if (map.find(nums[i]) != map.end()) {
vector<int> result = {map[nums[i]], i};
return result;
}
else {
map[target - nums[i]] = i;
}
}
}
A thorough writeup of this solution can be found here.
Congratulations @elsyr! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
You got a First Vote
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @elsyr! You received a personal award!
Click here to view your Board of Honor
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @elsyr! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit