Skip to main content
Code Review

Return to Revisions

2 of 2
Commonmark migration

C++ return the sum of the 2 smallest elements in a vector

Here is the description of the problem from codewars:

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.

For example, when an array is passed like [19,5,42,2,77], the output should be 7.

[10,343445353,3453445,3453545353453] should return 3453455.

Hint: Do not modify the original array.

And this is my solution which passed all tests.

// Returns the index of the smallest number.
int smallest(std::vector<int> numbers) {
 int smallest = 1;
 for(int i = 0; i < numbers.size(); i++) 
 {
 if(numbers[i] < numbers[smallest]) {
 smallest = i;
 }
 }
 return smallest;
}
long sumTwoSmallestNumbers(std::vector<int> numbers)
{
 int firstIndex = smallest(numbers);
 uint64_t first = numbers[smallest(numbers)];
 numbers.erase(numbers.begin() + firstIndex);
 uint64_t second = numbers[smallest(numbers)];
 return first + second;
}

While it's fairly fast and simple I feel like there is a way to do it while only looping over the list once and the hint about not modifying it seems to suggest that.

Qwertie
  • 325
  • 2
  • 8
lang-cpp

AltStyle によって変換されたページ (->オリジナル) /