Share my concise easy understanding solution


  • 1
    S

    // using hashmap

    vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> ans;
            unordered_map<int, int> hm;
            
            for (int i = 1; i <= numbers.size(); ++i) {
                if (hm.count(target - numbers[i-1]) != 0) {
                    ans.push_back(hm[target-numbers[i-1]]);
                    ans.push_back(i);
                    break;
                }
                hm[numbers[i-1]] = i;
            }
            
            return ans;
        }

Log in to reply
 

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