A 20ms C++ Solution Using Unordered_map


  • 1
    Y
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            int len = nums.size();
            vector<int> ans = {};
            unordered_map<int,int> mp;
            for(int i = 0; i < len ; i++) {
                ++mp[nums[i]] = i;
            }
            for(int j = 0; j < len; j++) {
                if((mp.find(target - nums[j]) != mp.end())&&(mp.find(target - nums[j])->second != j)) {
                    if(j < mp.find(target - nums[j])->second) {
                        ans.push_back(j + 1);
                        ans.push_back(mp.find(target - nums[j])->second + 1);
                    } else {
                        ans.push_back(mp.find(target - nums[j])->second + 1);
                        ans.push_back(j + 1);
                    }
                    return ans;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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