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 };
}