Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <unordered_map>
- using namespace std;
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- unordered_map<int, int> seenValueIndex; // whenever we observe a value, we'll keep its
- // value as key and index as value
- vector<int> pair; // resulted indexes
- for (int i = 0; i < nums.size(); i++)
- {
- int compliment = target - nums[i]; // sum - value at index
- if (seenValueIndex.find(compliment) != seenValueIndex.end())
- { // if found
- pair.push_back(seenValueIndex[compliment]);
- pair.push_back(i);
- break;
- }
- seenValueIndex[nums[i]] = i; // key = value, value = index
- }
- return pair;
- }
- };
- int main(void)
- {
- cout << "How many elements? : ";
- int size; cin >> size;
- vector<int> list;
- for (int i = 0; i < size; i++)
- {
- cout << "\nElement NO. " << (i + 1) << " : ";
- int element;
- cin >> element;
- list.push_back(element);
- }
- cout << "\nTarget sum : ";
- int target;
- cin >> target;
- Solution s;
- vector<int> result = s.twoSum(list, target);
- cout << endl << "Resultant pair (if exists): [";
- int count = 0;
- for (int i : result)
- {
- ++count;
- if (count % 2 != 0)
- {
- cout << i + 1 << ", ";
- }
- else
- {
- cout << i + 1;
- }
- }
- if (count == 0)
- cout << "-";
- cout << "]\n\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment