ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 查找数组中最大的三个元素 > 原文: [https://www.geeksforgeeks.org/find-the-largest-three-elements-in-an-array/](https://www.geeksforgeeks.org/find-the-largest-three-elements-in-an-array/) 给定一个包含所有不同元素的数组,找到最大的三个元素。 预期时间复杂度为`O(n)`,额外空间为`O(1)`。 **示例**: ``` Input: arr[] = {10, 4, 3, 50, 23, 90} Output: 90, 50, 23 ``` 下面是算法: ``` 1) Initialize the largest three elements as minus infinite. first = second = third = -∞ 2) Iterate through all elements of array. a) Let current array element be x. b) If (x > first) { // This order of assignment is important third = second second = first first = x } c) Else if (x > second) { third = second second = x } d) Else if (x > third) { third = x } 3) Print first, second and third. ``` 下面是上述算法的实现。 ## C ``` #include <stdio.h> #include <limits.h> /* For INT_MIN */ /* Function to print three largest elements */ void print3largest(int arr[], int arr_size) {     int i, first, second, third;     /* There should be atleast three elements */     if (arr_size < 3)     {         printf(" Invalid Input ");         return;     }     third = first = second = INT_MIN;     for (i = 0; i < arr_size ; i ++)     {         /* If current element is greater than first*/         if (arr[i] > first)         {             third = second;             second = first;             first = arr[i];         }         /* If arr[i] is in between first and second then update second  */         else if (arr[i] > second)         {             third = second;             second = arr[i];         }         else if (arr[i] > third)             third = arr[i];     }     printf("Three largest elements are %d %d %d\n", first, second, third); } /* Driver program to test above function */ int main() {     int arr[] = {12, 13, 1, 10, 34, 1};     int n = sizeof(arr)/sizeof(arr[0]);     print3largest(arr, n);     return 0; } /*This code is edited by Ayush Singla(@ayusin51)*/ ```