majority element

来源:互联网 发布:java判断是否为数字 编辑:程序博客网 时间:2024/04/20 17:00

实验2【实验任务】

A majority element in an array, A, of size N is anelement that appears more than N/2 times (thus, there is at most one). Forexample, the array

        3, 3, 4, 2,4, 4, 2, 4, 4

has a majority element (4), whereas the array

        3, 3, 4, 2,4, 4, 2, 4

does not. If there is no majority element, your programshould indicate this. Here is a sketch of an algorithm to solve the problem:

 

First, a candidate majority element is found (this is aharder part). This candidate is the only element that could possibly be themajority element.最多只有1个(反证法) The second step determines if thiscandidate is actually the majority. This is just a sequential search throughthe array. To find a candidate in the array, A, form a second array, B. Thencompare A1 and A2. If they are equal, add one of these to B; otherwise donothing. Then compare A3 and A4. Again if they are equal, add one of these toB; otherwise do nothing. Continue in this fashion until the entire array isread. Then recursively find a candidate for B; this is the candidate for A(why?).

a. How does therecursion terminate?

每一次递归都会使数组减小一半,最终减为0,算法结束

*b. How is the case where N is odd handled?

  N 为级数,则每一次都是奇数,最终剩下一个元素,算法结束得到主要元素

b. What is therunning time of the algorithm?

Log2(N)

c. How can we avoidusing an extra array B?

直接用A,把A开大一点,记录增长的长度 直接写在A的最小地方

*d. Write a program to compute the majority element.

#include<iostream>#include<stdio.h>using namespace std;int find(int arr[],int size){    if(size==1)    return arr[0];    else if(size==0)    return -1;    int index=0;    for(int i=0;i<size;i+=2)    {      if(arr[i]==arr[i+1])           arr[index++]=arr[i+1];       }    if(size%2==1)       arr[index++]=arr[size-1];    int temp=find(arr,index);      return temp;}int main(){  int arr[1000]={3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4,3,3,4,2,4,2,4,4};  int x=find(arr,strlen());//int 数组不能用任何的函数来调用返回长度,对于char 类型的数组,返回的是遇到第一个"\0" 为止,。所以不一定正确 ,因此需要知道数组的长度.  printf("x is %d\n",x);//stream.close(); system("pause"); return 0;   }