一个数组中有一个数字的次数超过了数组的一半,求出这个字符

来源:互联网 发布:淘宝情趣内衣评论晒图 编辑:程序博客网 时间:2024/04/29 11:22


解法一:一个数字出现的次数超过数组大小的一半,那么如果这是一个有序的数组,这个数字必定在数组中间的位置。
解法二:一个数字出现的次数超过数组大小的一半,也就是说,该数字出现的次数比其他数字出现次数的和还要多。那么,我们可以在遍历数组时设置两个变量result,times;result记录数组中的数字,times记录次数。当我们遍历下一个数字时,如果该数字与之前保存至result中的数字相同,则times++,反之times- -;如果times为0,则保存下一个数字至result,times置1。而我们要找的数字肯定是最后一次设置为result的数字。
具体代码看下面:

#include<iostream>using namespace std;int MoreThanHalfNum(int *arr, int size){    if (arr == NULL || size <= 0)        return 0;    int result = arr[0];    int times = 1;    for (int i = 1; i < size; i++)    {        if (times == 0)        {            result = arr[i];            times = 1;        }        else if (arr[i] != result)            times--;        else             times++;    }    return result;}int main(){    int arr[12] = { 2, 3, 2, 2, 2, 2, 2, 5, 4, 1, 2, 3 };    cout << MoreThanHalfNum(arr, 12) << endl;    system("pause");    return 0;}
阅读全文
0 0
原创粉丝点击