假设我们有一个n个元素的数组。我们必须在数组中找到第一个,第二个和第三个最小元素。第一个最小值是数组的最小值,第二个最小值是最小值,但大于第一个最小值,类似地,第三个最小值是最小值,但大于第二个最小值。
扫描每个元素,然后检查该元素,并关联第一,第二和第三最小元素条件的条件以解决此问题。
#include<iostream> using namespace std; int getThreeMins(int arr[], int n) { int first = INT_MAX, sec = INT_MAX, third = INT_MAX; for (int i = 0; i < n; i++) { if (arr[i] < first) { third = sec; sec = first; first = arr[i]; } else if (arr[i] < sec) { third = sec; sec = arr[i]; } else if (arr[i] < third) third = arr[i]; } cout << "First min = " << first << endl; cout << "Second min = " << sec << endl; cout << "Third min = " << third << endl; } int main() { int array[] = {4, 9, 18, 32, 12}; int n = sizeof(array) / sizeof(array[0]); getThreeMins(array, n); }
输出结果
First min = 4 Second min = 9 Third min = 12