在 C++ 中查詢陣列中最大的三個元素


在這個問題中,我們給定了一個包含 N 個無序元素的 arr[]。我們的任務是 *查詢陣列中最大的三個元素*。

讓我們舉個例子來理解這個問題,

Input : arr[] = {7, 3, 9, 12, 1}
Output : 12, 9, 7

解決方案方法

我們基本上需要找到陣列中三個最大的元素並打印出來。這可以透過多種方式完成,

方法 1

對於最大的三個元素,我們將建立三個元素來儲存它們的值,*max、max2 和 max3*,並將這些值設定為 arr[0]。

然後我們將迴圈從 i -> 1 到 n-1,對於每個元素

如果 (arr[i] > max) -> max3 = max2,max2 = max,max = arr[i]。

否則如果 (arr[i] > max2) -> max3 = max2,max2 = arr[i]。

否則如果 (arr[i] > max3) -> max3 = arr[i]。

在迴圈結束時,我們將列印所有三個值。

示例

程式說明我們解決方案的工作原理

#include <iostream>
using namespace std;
void findThreeLargestElements(int arr[], int arr_size){
   int max, max2, max3;
   max3 = max = max2 = arr[0];
   for(int i = 0; i < arr_size; i++){
      if (arr[i] > max){
         max3 = max2;
         max2 = max;
         max = arr[i];
      }
      else if (arr[i] > max2){
         max3 = max2;
         max2 = arr[i];
      }
      else if (arr[i] > max3)
         max3 = arr[i];
   }
   cout<<endl<<"Three largest elements of the array are "<<max<<", "<<max2<<", "<<max3;
}
int main(){
   int arr[] = {15, 2, 7, 86, 0, 21, 50};
   int n = sizeof(arr) / sizeof(arr[0]); 
   cout<<"The array is : ";
   for(int i = 0; i < n; i++) 
      cout<<arr[i]<<"\t"; 
   findThreeLargestElements(arr, n);
   return 0;
}

輸出

The array is : 15 2 7 86 0 21 50 Three largest elements of the array are 86, 50, 21

方法 2

解決問題的另一種方法是透過對陣列進行排序,然後列印陣列的前三個元素,它們是三個最大的元素。

演算法

**步驟 1** - 使用排序技術對陣列進行排序。

**步驟 2** - 列印前三個元素:arr[0]、arr[1]、arr[2]

示例

程式說明我們解決方案的工作原理

#include <bits/stdc++.h>
using namespace std;
void findThreeLargestElements(int arr[], int n){
   sort(arr, arr + n, std::greater<>());
   int j = 0;
   cout<<"\nThree largest elements are ";
   for(int i = 0; i < n; i++){ 
      if(arr[i] != arr[i+1]){ 
         cout<<arr[i]<<" "; 
         j++;
      }
      if(j == 3){
         break;
      }
   }
}
int main(){
   int arr[] = {15, 2, 7, 86, 0, 21, 50, 53, 50};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The array is : ";
   for(int i = 0; i < n; i++)
      cout<<arr[i]<<"\t";
   findThreeLargestElements(arr, n);
   return 0;
}

輸出

The array is : 15 2 7 86 0 21 50 53 50
Three largest elements are 86 53 50

更新於:2022-01-28

9K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.