Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<int> twoSum(vector<int>& nums, int target) {
  4. unordered_map<int,int> numsMap;
  5. vector<int> result;
  6. int length = nums.size();
  7.  
  8. for (int i = 0; i<length; i++) {
  9. numsMap[nums[i]] = i;
  10. }
  11.  
  12. for (int i = 0; i<length; i++) {
  13. /* If we call find(), it will return the last Key-Value
  14. ex: numsMap[6] = 3;
  15. numsMap[6] = 6;
  16. numsMap[6] = 1;
  17. ==> numsMap.find(6) will return 'numsMap[6] = 1'
  18. */
  19. auto it = numsMap.find(target-nums[i]);
  20. /* Consider this case:
  21. [3, 2, 4] , target = 6
  22.  
  23. If we don't add 'it->second > i'
  24. it will return [0, 0]
  25. because numsMap.find(3) return 'numsMap[3] = 0'
  26. */
  27. if (it != numsMap.end() && it->second>i) {
  28. result.push_back(i);
  29. result.push_back(it->second);
  30. break;
  31. }
  32. }
  33. return result;
  34. }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement