#include <stdio.h> #include <stdlib.h> /* 给定一个n个整型元素的数组a, 其中有一个元素出现次数超过n/2, 求这个元素。 */ int getExceedHalf(int *numbers, int length); int main(){ int n; while (printf("Please input n:\n"), fflush(stdin), scanf("%d", &n) != EOF){ if (n < 1){ printf("Please input a bigger number.\n"); continue; } int *numbers = (int*)malloc(n*sizeof(int)); printf("Please input %d number:\n",n); for (int i = 0; i < n; ++i) scanf("%d",numbers + i); printf("The number is: %d\n",getExceedHalf(numbers,n)); } system("pause"); return 0; } int getExceedHalf(int *numbers, int length){ int number = numbers[0]; int count = 1; for (int i = 1; i < length; ++i){ if (numbers[i] == number) count++; else if (count > 0) count--; else{ count = 1; number = numbers[i]; } } return number; }
时间: 2024-10-28 02:32:45