2 Sum

code


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ret;
        if(nums.size() == 0)
        {
            return ret;
        }

        map<int, int> hash;
        for(int i = 0; i<nums.size(); i++)
        {
            int need = target - nums[i];
            if(hash.find(need) != hash.end())
            {
                ret.push_back(hash[need]);
                ret.push_back(i);
                return ret;
            }

            hash[nums[i]] = i;
        }

        return ret;
    }
};

results matching ""

    No results matching ""