10Leetcode---find over half

一. 题目

已知:数组中有一个数字出现的次数超过了数组长度的一半,求:出这个数   

思路:算法时间复杂度O(n),另外需要两个辅助变量 tmp count, 其中tmp:临时存放数组中的数据, count用于存储某个数出现次数。

开始 tmp存储数组的第一个数, count=0   若数组出现的数==tmp  count++  否则count-- 若count==0,把当前数组中的值赋给tmp;由于题目中存在一个数的个数超过length/2,所以经过count++和count--相互抵消后,最终count>=1,而tmp中存放的就是出现最多的那个数。

#include<stdio.h>
#include<iostream>
#include<stdlib.h>

using namespace std;

int FindOverHalf(int A[], int len)
{
    if(NULL==A || len<=0) return -1;

    int tmp, count=0;
    for(int i=0;i<len;i++)
    {
        if(count==0) tmp=A[i];
        if(k==A[i])
            count++;
        else
            count--;
    }
    return tmp;
}

int main(){
    int len = 10;
    int a[10] = {4,5,5,2,3,5,2,5,5,5};
    int result = FindOverHalf(a,len);
    cout<<result<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/qinghange/article/details/82961821
今日推荐