题目是这样的:"给定一个数组,输出数组和中的最大的两个数(手写)"
idea
要想找到数组中的极值(本例中要求最大值);是需要把所有的值都遍历过,至于遍历几遍就看怎么遍历了。针对本例中的找出最大的两个数时,我一开始的想法就是两次for循环,一次循环找出数组中的最大值,下一次循环找出数组中的次大值;叭叭叭就上代码
int* find(int arr[], int length) {
if(arr == NULL || length <= 0){
cout<<" please input correct array, big bro!"<<endl;
exit;
}
static int max[2];
for (int i = 0; i < 2; i++) {
for (int j = length - 1; j > i; j--) {
if (arr[j] > arr[j - 1]) {
int tmp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = tmp;
}
}
max[i] = arr[i];
}
return max;
}
可能是算法规模不大,思维也不好扩散,后来还是一直想这个问题,就找两个最大数,是不是非得要遍历两遍?反正之前的做法是每次都有元素比较,那就一次循环把该比较的都给比较了呗,
过程:
- 原数组的每一个元素值先和我们给出的已知的最大的值比较,如果比我们给出的最大的值还要大,那当前元素值就复制给我们的最大数
- 如果当前元素值比我们已知的最大的数小,就和我们已知的次大是数比较。如果当前数组元素比我们已知的次大的数要大,那么当前元素就赋值给我们的次大值
叭叭叭,又上代码:
#include <iostream>
#include <vector>
using namespace std;
int* find(int arr[], int length) {
if (arr == NULL || length <= 1) {
cout << " please input correct array, big bro!" << endl;
exit(1);
}
static int max[2] = {0, 0};
for (int index = 0; index < length; index++) {
if (max[0] < arr[index]) {
max[0] = arr[index];
} else if (max[1] < arr[index]) {
max[1] = arr[index];
}
}
return max;
}
int main() {
int arr[] = {10, 7, 82, 9, 13, 5, 2, 34, 54, 3, 26, 6, 37, 6, 48, 11};
// int arr[] = {10, 7};
// int arr[] = {10};
cout << "------find the big two number------" << endl;
int length = sizeof(arr) / sizeof(arr[0]);
int* max = find(arr, length);
for (int i = 0; i < 2; i++) {
cout << " hia = " << *(max + i) << endl;
}
}
本地验证通过。