序列主元素问题 | 数据结构常见小题03

问题说明

当一个整数序列中某个元素的数量大于整个序列元素个数一半时
该元素为序列的主元素,发现一个序列的主元素(长度已知)

算法说明

方法一:先排序后统计的方法

先对序列进行排列,然后统计个数
时间复杂度O(nlog(n))

int findMainElement1(int A[],int n){
    //冒泡排序
    int temp;
    for(int i=0; i<n; i++){
        for(int j=i; j<n-i-1; j++){
            if(A[j]>A[j+1]){
                temp = A[j];
                A[j] = A[j+1];
                A[j+1] = temp;
            }
        }
    }
    //统计是否存在主元素
    for(int i = 0; i<=n/2; i++){
        if(A[i]==A[i+n/2]){
            return A[i];
        }
    }
    return -1;
}

方法二:先扫描后检查的方法

使用int e存储可能是主元素的元素,使用count计数
扫描第一个元素,e存储,count+1
下一个元素若是e,count+1;若不是count-1
count为0时,c放入新元素,count+1
最后检查一遍,c是否是主元素
时间复杂度为O(n)

int findMainElement2(int A[],int n){
    int c,count=0;
    c = A[0];
    count++;
    for(int i = 1; i<n; i++){
        if(c == A[i]){
            count++;
        }
        else{
            count--;
        }
        if(count == 0){
            c = A[i];
            count++;
        }
    }
    count = 0;
    for(int i = 0; i<n; i++){
        if(c == A[i]){
            count++;
        }
    }
    if(count > n/2){
        return c;
    }
    else{
        return -1;
    }
}

执行示例

#include<iostream>
using namespace std;

int findMainElement1(int A[],int n){
    //冒泡排序
    int temp;
    for(int i=0; i<n; i++){
        for(int j=i; j<n-i-1; j++){
            if(A[j]>A[j+1]){
                temp = A[j];
                A[j] = A[j+1];
                A[j+1] = temp;
            }
        }
    }
    //统计是否存在主元素
    for(int i = 0; i<=n/2; i++){
        if(A[i]==A[i+n/2]){
            return A[i];
        }
    }
    return -1;
}

int findMainElement2(int A[],int n){
    int c,count=0;
    c = A[0];
    count++;
    for(int i = 1; i<n; i++){
        if(c == A[i]){
            count++;
        }
        else{
            count--;
        }
        if(count == 0){
            c = A[i];
            count++;
        }
    }
    count = 0;
    for(int i = 0; i<n; i++){
        if(c == A[i]){
            count++;
        }
    }
    if(count > n/2){
        return c;
    }
    else{
        return -1;
    }
}

int main(){
    int S[8]={3,4,4,3,4,3,4,4};
    int Element1 ,Element2;
    Element1=findMainElement1(S , 8);
    Element2=findMainElement2(S , 8);
    cout <<Element1 <<endl;
    cout <<Element2 <<endl;
    return 0;
}

示例结果为:
4
4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值