Leetcode – Two Sums

Inspired by my fellow developers, I’ve decided to try a couple of challenges every week.

Starting at the very beginning:

Name: Two Sums
Difficulty: Easy
Description: Return the indexes of the two numbers which add up to the target number.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

I used a simple brute force solution.

vector<int> twoSum(vector<int>& nums, int target) {
    if (nums.size() < 2) return { -1, -1 };
        
    auto end = nums.end() - 1;        

    for (auto i = nums.begin(); i < end; ++i) {
        for(auto j = i + 1; j < nums.end(); ++j) {
            if (target == *i + *j) return { 
                static_cast<int>(i - nums.begin()), 
                static_cast<int>(j - nums.begin()) 
            };
        }
    }

    return { -1, -1 };
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s