🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 查找数组中的最小和第二个最小元素 > 原文: [https://www.geeksforgeeks.org/to-find-smallest-and-second-smallest-element-in-an-array/](https://www.geeksforgeeks.org/to-find-smallest-and-second-smallest-element-in-an-array/) 编写高效的 C 程序以查找数组中的最小和第二个最小元素。 ![](https://img.kancloud.cn/d6/d0/d6d0d58c7341579d4842937b47744b7c_1024x512.png) **示例**: ``` Input: arr[] = {12, 13, 1, 10, 34, 1} Output: The smallest element is 1 and second Smallest element is 10 ``` **简单解决方案**是按递增顺序对数组进行排序。 排序数组中的前两个元素将是两个最小的元素。 该解决方案的时间复杂度为`O(N log N)`。 **更好的解决方案**是扫描数组两次。 在第一次遍历中找到最小元素。 将此元素设为`x`。 在第二遍历中,找到大于`x`的最小元素。 该解决方案的时间复杂度为`O(n)`。 上面的解决方案需要两次遍历输入数组。 **有效解决方案**可以在一次遍历中找到最少两个元素。 下面是完整的算法。 **算法**: ``` 1) Initialize both first and second smallest as INT_MAX *first* = *second* = INT_MAX 2) Loop through all the elements. a) If the current element is smaller than *first*, then update *first* and *second*. b) Else if the current element is smaller than *second* then update *second* ``` **实现**: ## C++ ```cpp // C++ program to find smallest and  // second smallest elements  #include <bits/stdc++.h> using namespace std; /* For INT_MAX */ void print2Smallest(int arr[], int arr_size)  {      int i, first, second;      /* There should be atleast two elements */     if (arr_size < 2)      {          cout<<" Invalid Input ";          return;      }      first = second = INT_MAX;      for (i = 0; i < arr_size ; i ++)      {          /* If current element is smaller than first          then update both first and second */         if (arr[i] < first)          {              second = first;              first = arr[i];          }          /* If arr[i] is in between first and second          then update second */         else if (arr[i] < second && arr[i] != first)              second = arr[i];      }      if (second == INT_MAX)          cout << "There is no second smallest element\n";      else         cout << "The smallest element is " << first << " and second "             "Smallest element is " << second << endl;  }  /* Driver code */ int main()  {      int arr[] = {12, 13, 1, 10, 34, 1};      int n = sizeof(arr)/sizeof(arr[0]);      print2Smallest(arr, n);      return 0;  }  // This is code is contributed by rathbhupendra ```