majority element

实验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;   
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值