Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- unordered_map<int,int> numsMap;
- vector<int> result;
- int length = nums.size();
- for (int i = 0; i<length; i++) {
- numsMap[nums[i]] = i;
- }
- for (int i = 0; i<length; i++) {
- /* If we call find(), it will return the last Key-Value
- ex: numsMap[6] = 3;
- numsMap[6] = 6;
- numsMap[6] = 1;
- ==> numsMap.find(6) will return 'numsMap[6] = 1'
- */
- auto it = numsMap.find(target-nums[i]);
- /* Consider this case:
- [3, 2, 4] , target = 6
- If we don't add 'it->second > i'
- it will return [0, 0]
- because numsMap.find(3) return 'numsMap[3] = 0'
- */
- if (it != numsMap.end() && it->second>i) {
- result.push_back(i);
- result.push_back(it->second);
- break;
- }
- }
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement