https://leetcode.com/problems/two-sum/

1. Use hashtable/hashmap:

  1. // 16 ms 10.3 MB
  2. class Solution {
  3. public:
  4. vector<int> twoSum(vector<int>& nums, int target) {
  5. unordered_map<int, int> hashmap; //nums, index_of_nums
  6. int n = nums.size();
  7. for(int i = 0; i < n; i++)
  8. hashmap[nums[i]] = i;
  9. for(int i = 0; i < n; i++){
  10. unordered_map<int, int>::iterator got = hashmap.find(target-nums[i]);
  11. if(got != hashmap.end() && (i != got->second))
  12. return {i, got->second};
  13. }
  14. return {};
  15. }
  16. };