标签:style blog class code color width
29. 数组中出现次数超过一半的数字.
方法a. 排序取中 O(nlogn).
方法b. partition 函数分割找中位数 >=O(n).
方法c. 设计数变量,扫描一遍。 O(n).
#include <stdio.h> bool Invalid_Input = false; int getNumber(int data[], int length){ Invalid_Input = false; if(!data || length < 1) { Invalid_Input = true; return 0; } int count = 1, value = data[0]; for(int i = 1; i < length; ++i) { if(count == 0){ value = data[i]; count = 0; }else if(data[i] == value){ ++count; }else --count; } return value; } int main(){ int numbers[] = {2, 2, 2, 2, 6, 6, 6, 6, 6}; int value = getNumber(numbers, sizeof(numbers) / 4); if(value && !Invalid_Input) printf("%d\n", value); return 0; }
Chap5: question: 29 - 31,布布扣,bubuko.com
标签:style blog class code color width
原文地址:http://www.cnblogs.com/liyangguang1988/p/3703688.html