#Code Review: Two Sums

37 messages · Page 1 of 1 (latest)

astral zealot
#
vector<int> twoSum(vector<int> &nums, int target)
{
        unordered_map<int, int> seen;

        for (int i = 0; i < nums.size(); i++)
        {
                if (seen.find(target - nums[i]) != seen.end())
                {
                        return {seen[target - nums[i]], i};
                }
                seen[nums[i]] = i;
        }

        return {};
}

Is there a better way to write this code using the STL (<algorithm> maybe)?

#

Maybe the there is a better option tham using the

.find()
tranquil magnet
astral zealot
tranquil magnet
#

nums should be std::span<const int>

#

that would be more flexible

astral zealot
#

but like span were introcued in c++20?

#

no?

#

I try to keep myself on C++17 max

tranquil magnet
#

why

#

C++20 is pretty much the sane default now

astral zealot
#

Cause it's too much to go from C++98 to C++20

tranquil magnet
#

soon I'll be recommending C++23

astral zealot
#

I want to understand step by step

tranquil magnet
#

there's very little benefit to that tbh, just learn the idiomatic way now

astral zealot
#

Is it a bad idea?

tranquil magnet
#

how it was done historically is more of a side note

astral zealot
#

but C++20 has huge changes

tranquil magnet
#

std::span isn't a particularly complicated feature either, it's basically just a pointer and a size

astral zealot
#

@tranquil magnet so for you

#

I should learn C++20

#

and forget about the others?

tranquil magnet
#
pair<size_t, size_t> twoSum(span<const int> nums, int target)
{
    constexpr size_t npos(-1);
    unordered_map<int, size_t> seen;

    for (size_t i = 0; i < nums.size(); i++)
    {
        const int other = target - nums[i];
        if (seen.contains(other))
        {
            return pair<size_t, size_t>{seen[other], i};
        }
        seen[nums[i]] = i;
    }

    return {npos, npos};
}
tranquil magnet
#

most language features exist because the language had a deficiency up until they were added

#

so you're just using a deficient version for no gain if you avoid C++20

astral zealot
#

is it really important to put const int instead of const?

tranquil magnet
#

where

astral zealot
#

const int other = target - nums[i];

tranquil magnet
#

yeah, C++ doesn't have implicit int

#

it wouldn't compile with just const

#

you could use const auto though

#

also I'm not sure if your code handles the case where nums[0] + nums[0] == target

#

or more generally, if nums[0] * 2 == target, if it's allowed to just use the same number twice

#

if not, you could also return {0, 0} to indicate failure

astral zealot
#

Most of the jobs I've seen ask for C++17 max skills

#

!resolved