Last active
January 2, 2016 11:29
-
-
Save iziang/8296718 to your computer and use it in GitHub Desktop.
从前向后遍历数组,每一个元素都先和max比较
(1)如果大于max,则更新max和second_max
(2)如果小于max,再和second_max比较,如果大于second_max,则更新second_max
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
int second_max_length(int array[], const int length, int &second_max) | |
{ | |
if((array == NULL) || (length < 2)){ | |
return 0; | |
} | |
int i; | |
//本来采用MIN = -1,现在通过比较前两个元素的大小,来确定max和second_max即可 | |
//前两个元素的和,减去max的值,即可得到second_max的值 | |
int max = array[0] > array[1] ? array[0]:array[1]; | |
second_max = array[0] + array[1] - max; | |
for(i = 2; i < length; i++){ | |
if(array[i] > max){ | |
second_max = max; | |
max = array[i]; | |
} | |
else if(array[i] > second_max){ | |
second_max = array[i]; | |
} | |
} | |
return 1; | |
} | |
int main() | |
{ | |
int array[1000]; | |
int length, second_max; | |
scanf("%d", &length); | |
int i; | |
for(i = 0; i < length; ++i){ | |
scanf("%d", array + i); | |
} | |
if(second_max_length(array, length, second_max)){ | |
printf("%d\n", second_max); | |
} | |
else{ | |
printf("array error\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment