面试-剑指offer-数组中出现次数超过一半的数字

来源:互联网 发布:移动4g网络怎么设置dns 编辑:程序博客网 时间:2024/06/05 06:32

题目

数组中有一个数字出现的次数超过数组长度的一般,请找出这个数字。

思路

  • 解法一:基于Partition函数的O(n)算法
  • 数组中有一个数字出现的次数超过了数组长度的一般。如果把这个数组排序,那么排序之后位于数组中间的数字一定就是那个出现次数超过数组长度一半的数字。也就是说,这个数字就是统计学上的中位数,即长度为n的数组中第n/2大的数字。我么有成熟的O(n)的算法得到数组中任意第k大的数字。

快速排序

思想:先在数组中随机选择一个数字,然后调整数组中数字的顺序,使得比选中的数字小的数字都排在它的左边,比选中的数字大的数字都排在它的右边。如果这个选中的数字的下标刚好是n/2,那么这个数字就是数组的中位数。如果它的下标大于n/2,那么中位数应该位于它的左边,我们可以接着在它的左边部分的数组中查找。如果它的下标小于n/2,那么中位数应该位于他的右边,我们可以接着在它的右边部分的数组中查找。这是一个典型的递归问题。

  • 解答二:根据数组特点找出O(n)的算法
  • 数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现次数的和还要多。因此可以考虑在遍历数组的时候保存两个值:一个是数组的一个数字,一个是次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1;如果下一个数字和我们之前保存的数字不同,则次数减1.如果次数为零,我们需要保存下一个数字,并把次数设为1.由于我们要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。
#include <iostream>using namespace std;int Partition(int *A,int low,int high){    int pivotkey=A[low];    while (low<high)    {        while (low<high&&A[high]>=pivotkey)        {            high--;        }        A[low]=A[high];        while (low<high&&A[low]<=pivotkey)        {            low++;        }        A[high]=A[low];    }    A[low]=pivotkey;    return low;}bool confirmNum(int *array,int number,int len){    int time=0,i;    for (i=0;i<len;i++)    {        if (array[i]==number)        {            time++;        }    }    if (time*2>len)    {        return true;    }    else        return false;}void MoreThanHalfArray(int *array,int len){    int middle=len/2;    int index,start=0,end=len-1;    index=Partition(array,start,end);    while (index!=middle)    {        if (index>middle)        {            end=index-1;            index=Partition(array,start,end);        }        else        {            start=index+1;            index=Partition(array,start,end);        }    }    int result=array[middle];    if (confirmNum(array,result,len))    {        cout<<"exsit this element is "<<result<<endl;    }    else        cout<<"not found this element\n";}void MoreThanHalf(int *array,int len){    int i;    int result,time = 0;    for(i = 0;i < len;i++){        if(time == 0){            result = array[i];            time = 1;        }        else if(array[i] == result){            time++;        }        else            time--;    }    if(confirmNum(array,result,len)){        cout<<"exist this element is "<<result<<endl;    }    else        cout<<"not found this element\n";}int main(){    int array[]={1,2,3,2,2,2,5,4,2};    MoreThanHalfArray(array,9);    MoreThanHalf(array,9);    return 0;}

由于等于二分之一肯定大于三分之一,估可以将此题转化为数组中有一个数字出现的次数超过了数组长度的三分之一,找出这个数字。

阅读全文
0 0
原创粉丝点击