首页 > 代码库 > Chap5: question: 29 - 31

Chap5: question: 29 - 31

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 = http://www.mamicode.com/data[0];"color: blue;">for(int i = 1; i < length; ++i)
    {
        if(count == 0){
            value = http://www.mamicode.com/data[i];"color: blue;">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 = http://www.mamicode.com/getNumber(numbers, sizeof(numbers) / 4);
    if(value && !Invalid_Input)
        printf("%d\n", value);
    return 0;
}
shot