Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาองค์ประกอบทั้งหมดในอาร์เรย์ที่มีองค์ประกอบมากกว่าอย่างน้อยสองตัวใน C++

สมมติว่ามีอาร์เรย์ของตัวเลข n ตัว เราต้องหาองค์ประกอบทั้งหมดในอาร์เรย์ ซึ่งมีองค์ประกอบที่มากกว่ามันอย่างน้อยสองตัว ถ้าอาร์เรย์เป็น A = [2, 8, 7, 1, 5] ผลลัพธ์จะเป็น [2, 1, 5]

เพื่อแก้ปัญหานี้ เราจะหาองค์ประกอบที่มากเป็นอันดับสอง (Second Maximum) แล้วพิมพ์องค์ประกอบทั้งหมดที่น้อยกว่าหรือเท่ากับค่าอันดับสอง

ตัวอย่าง

#include <iostream> 
using namespace std; 

void searchElements(int arr[], int n) {
    int first_max = INT_MIN, second_max = INT_MIN;
    for (int i = 0; i < n; i++) {
        if (arr[i] > first_max) {
            second_max = first_max;
            first_max = arr[i];
        } else if (arr[i] > second_max)
            second_max = arr[i];
    }
    for (int i = 0; i < n; i++)
        if (arr[i] < second_max)
            cout << arr[i] << " ";
}

int main() {
    int arr[] = { 2, 9, 1, 7, 5, 3, 17 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Elements are: ";
    searchElements(arr, n);
}

ผลลัพธ์

Elements are: 2 1 7 5 3