C++ O(n) Solution With Hash ,Beats 68% Submissions


  • 0
      class Solution {
      public:
        vector<int> twoSum(vector<int>& nums, int target) {
          unordered_map<int,int> search_hash; // map<nums,location>
          vector<int> result(2);
          typename unordered_map<int,int>::iterator res_itr;
          for (int i = 0; i < nums.size() ; i++)
            search_hash.insert(make_pair(nums[i], i));
          for (int i = 0; i < nums.size() ; i++) {
            if ((res_itr = search_hash.find(target - nums[i])) != search_hash.end() && i != res_itr->second) {
            result[0] = min(i,res_itr->second);
            result[1] = max(i,res_itr->second);
            break;
          }
          }
          return result;
    
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.