Problem
Answer (Brute Force)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size() - 1; i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};
To solve this problem, it is necessary to sum each pair of elements in the nums array.
For instance:
nums = [1, 2, 3, 4]
target = 5
1 + 2 = 3;
2 + 3 = 5;
3 + 4 = 7;
As a result, we need to use a double for loop.
The first loop iterates over the nums array up to the second to last element, because we need to sum two elements and thus the last element doesn't need to be included in the first loop.
The second loop starts at position i + 1 to avoid repeating the same combination twice.
Lastly, we return the indices of the two elements in the form of a vector when the sum of these two elements equals the target argument.
In the statement return {i, j}, {i, j} creates a vector containing i and j elements.
Top comments (0)