'why is it coded by this way in leetcode? [duplicate]


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

the above is the code in leetcode i saw,look at the "return {};" this line,i think that it is return a empty list,but it is astonish me that this function's return value is not empty and it is for working.can anyone explain to me why?

Thanks in advance.

c++


Solution 1:[1]

look at the "return {};" this line,i think that it is return a empty list

An empty vector to be precise, yes.

but it is astonish me that this function's return value is not empty and it is for working.can anyone explain to me why?

Look at the other return statement:

return {it->second, i};

That one doesn't return an empty vector.


P.S. Since the function always returns either 2 integers or 0 integers, std::vector is probably a poor choice for the return type.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eerorika