在O(n)时间复杂度内找到出现超过一半的数
#include<iostream> using namespace std; bool solver(const int a[],const int n, int & num) { if(NULL == a || 0>= n) return false; ////注意,是小写~ int count = 0; int com = a[0]; for(int i = 1;i<n;i++) { if(0 == count) { com = a[i]; count++; } else{ if(a[i] == com) count++; else count--; } } num = com; return true; } int main() { int a[] = {1,2,3,3,3,3,3,3,4}; int temp; solver(a,9,temp); cout<<temp; }
berkeleysong
posted on 2014-05-18 19:29 berkeleysong 阅读(133) 评论(0) 编辑 收藏 举报