数组中出现次数超过一半的数字
2013-06-18 10:48
183 查看
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
#include <stdio.h> bool input_invalid = false;//全局变量,标识输入是否非法,因为find_num函数返回0不知道是返回0值还是因为输入错误返回0,需要这么一个标识位 bool check(int a[], int len) { input_invalid = false; if(a==NULL || len<=0) input_invalid = true; return input_invalid; } bool check_result(int a[], int len, int result)//判断找到的result是不是在数组中出现次数超过半数以上 { bool flag = false; int i; int times=0; for(i=0;i<len;i++) { if(a[i]==result) times++; } if(times*2 <= len) { input_invalid=true; flag = true; } return flag; } int find_num(int a[], int len) { if(check(a,len)) return 0; int times = 1;//数字出现的次数 int result = a[0];//result初始化 int i; for(i=1;i<len;i++) { if(times==0) { result = a[i]; times = 1; } else if(a[i]==result) times++; else times--; } if(check_result(a,len,result)) return 0; return result; } int main() { int a[] = {1,2,3,2,2,2,5,4,2}; int len = sizeof(a)/sizeof(int); int i; printf("数组值为:\n"); for(i=0;i<len;i++) printf("%d\t",a[i]); printf("\n"); int result = find_num(a,len); if(input_invalid) { printf("输入非法!\n"); } else { printf("数组中出现次数超过一半的数字是:%d\n",result); } return 0; }
相关文章推荐
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字(算法)
- 数组中出现次数超过一半的数字
- 数组中超过出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 剑指Offer(java版):数组中出现次数超过一半的数字
- 九度OJ-题目1370:数组中出现次数超过一半的数字
- [剑指Offer]数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数据结构练习(35)数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 基于partition——最小的K个数、数组中出现次数超过一半的数字
- 【算法习作】已知有一个数字在某数组中出现次数超过一半,求这个数
- 剑指offer-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 剑指offer 面试题29—数组中出现次数超过一半的数字
- 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字