内容中心

2026年评价高的东莞异性冰盒深度厂家推荐-东莞市鑫方冷链科技有限公司

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

  1. Initialization: Start with two variables, largest and second_largest, initialized to the smallest possible integer value (INT_MIN from the <climits> header). This ensures any input number will be larger initially.
  2. Reading Input: Read each integer one by one (we don't need to store all numbers as we process them immediately).
  3. Updating Values:
    • If the current number is greater than largest, update second_largest to largest and largest to the current number.
    • If the current number is equal to largest, check if second_largest is smaller than largest and update second_largest to largest (to handle duplicates).
    • If the current number is greater than second_largest but not larger than largest, update second_largest to the current number.
  4. 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 largest and second_largest.
  • Handling Duplicates: When a number equal to largest is encountered, we update second_largest to largest if 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.

东莞市鑫方冷链科技有限公司

东莞市鑫方冷链科技有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?