剑指offer之面试题29数组中出现次数超过一半的数字

来源:互联网 发布:相关系数软件 编辑:程序博客网 时间:2024/05/16 18:47

问题描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

例如:

输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2.

实现代码如下:

#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <limits.h>int findNumber(int *a,int n){if(a==NULL || n ==0){return INT_MIN;}int count = 0;int i;int key =a[0];for(i=1;i<n;i++){if(key==a[i]){count++;}else if(count>1){count--;}else if(count==1){key=a[i];}}return key;}int main(int argc, char *argv[]){int a[]={1,2,1,2,2,2,3};int n=sizeof(a)/sizeof(int);int key = findNumber(a,n);printf("%d\n",key);return 0;}

上面的算法的时间复杂度是O(n),空间复杂度是O(1)。

参考资料
剑指offer

备注
转载请注明出处:http://blog.csdn.net/wsyw126/article/details/51383580
作者:WSYW126

0 0
原创粉丝点击