Find the second largest number in a vector
Description: Find the second largest number in {12, 35, 1, 10, 34, 1} without sorting.
Hint:
- Keep
largestandsecond, and update both in one loop.
Solution
#include <climits>
#include <iostream>
#include <vector>
int second_largest(const std::vector<int>& v) {
int largest = INT_MIN, second = INT_MIN;
for (int n : v) {
if (n > largest) {
second = largest;
largest = n;
} else if (n > second && n != largest) {
second = n;
}
}
return second;
}
int main() {
std::cout << second_largest({12, 35, 1, 10, 34, 1}) << '\n';
std::cout << second_largest({5, 5, 5, 2}) << '\n';
}
Output
34
2
How it works
- When a bigger value comes, the old biggest becomes the second one.
Read C++ Vectors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |