13ms solution c++


  • 0
    P

    class Solution {
    public:
    vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> result;
    unordered_map<int,int> hash;
    for(int i=0;i<nums.size();i++)
    {
    int numToFind=target-nums[i];
    if(hash.find(numToFind)!=hash.end())
    {
    result.push_back(i);
    result.push_back(hash[numToFind]);
    return result;
    }
    hash[nums[i]]=i;
    }
    return result;
    }
    };


  • 0
    B

    I'm confused how this works, I don't see were hash is initialized to the values in nums.
    you do hash.find(numToFind) you pass in just an index, but how does hash know the values of nums?


  • 0
    P

    @bidwell i am finding the number (int numToFind=target-nums[i]) in the hash. if it is there then it will push the result in the result else the
    statement(hash[nums[i]]=i;) will add the current number to the hash. in this way hash will be updated.


Log in to reply
 

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