To solve this problem, we need to find the largest and second largest numbers from a list of 10 integers. The solution should handle both distinct and duplicate values correctly.
Approach
- Initialization: Start with two variables,
largestandsecond_largest, initialized to the smallest possible integer value (INT_MIN from the<climits>header). This ensures any input number will be larger initially. - Reading Input: Read each integer one by one (we don't need to store all numbers as we process them immediately).
- Updating Values:
- If the current number is greater than
largest, updatesecond_largesttolargestandlargestto the current number. - If the current number is equal to
largest, check ifsecond_largestis smaller thanlargestand updatesecond_largesttolargest(to handle duplicates). - If the current number is greater than
second_largestbut not larger thanlargest, updatesecond_largestto the current number.
- If the current number is greater than
- Output: Print the largest and second largest numbers.
Solution Code
#include <iostream>
#include <climits>
using namespace std;
int main() {
int largest = INT_MIN;
int second_largest = INT_MIN;
for (int i = 0; i < 10; ++i) {
int num;
cin >> num;
if (num > largest) {
second_largest = largest;
largest = num;
} else if (num == largest) {
if (second_largest < largest) {
second_largest = largest;
}
} else if (num > second_largest) {
second_largest = num;
}
}
cout << largest << " " << second_largest << endl;
return 0;
}
Explanation
- Initialization: Using INT_MIN ensures that any input number will be larger than the initial values of
largestandsecond_largest. - Handling Duplicates: When a number equal to
largestis encountered, we updatesecond_largesttolargestif it was smaller, which correctly handles cases where there are multiple instances of the largest number. - Efficiency: The algorithm runs in O(n) time complexity (n=10), which is optimal for this problem as we process each number exactly once.
This approach efficiently finds the desired values while handling all edge cases, including duplicates and negative numbers. The solution is straightforward and easy to understand.


作者声明:本文包含人工智能生成内容。