13 ms O(n) solution


  • 0
    N
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> result; // This will store the result
            unordered_map<int, int> m; //for mapping the indices with the values //Note an unordered_map is enough (hashMap)
            for(int i=0;i<nums.size();i++){
                if(m.find(target-nums[i])!=m.end()){ // That means these two add to the target
                    result.push_back(m[target-nums[i]]);
                    result.push_back(i);
                    return result;
                }
                m[nums[i]] = i; // adding values to the hash table
            }
            return result;
        }
    };
    

Log in to reply
 

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