C++ solution using std::unordered_map


  • 0
    A
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int,int> hash;
            unordered_map<int,int>::iterator got;
            int len = nums.size();
            int idx1, idx2;
            
            for (int i = 0; i < len; i++) {
                got = hash.find(nums[i]);
                if (got == hash.end()) {
                    hash.insert(make_pair(nums[i],i));
                } else {
                    got->second = i;
                }
            }
            
            for (vector<int>::const_iterator it = nums.begin(); it != nums.end(); ++it) {
                if (hash.count(target-*it)) {
                    idx1 = (it - nums.begin());
                    idx2 = hash[target-*it];
                    if (idx1 != idx2) {
                        break;
                    }
                }
            }
            
            return {idx1,idx2};
        }
    };
    

Log in to reply
 

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