数组中的主元素

主元素的概念是一个元素的出现次数占50%以上

快排方法,复杂度O(nlogn)

占50%,所以中间元素一定是主元素

int get(int A[], int n) {
    sort(A,A+n);
    return A[n/2];
}


利用主元素的特性求已知有主元素的数组的主元素,复杂度O(n)

因为其占50%以上,出现一次得++,不同得--,所以最后保留下来的一定是主元素


上代码,不懂的自己理解

int get(int A[], int n) {
    int result, cnt;
    result = A[0]; cnt = 1;
    for(int i=1; i<n; i++) {
        if(A[i] == result) {
            cnt++;
        }
        else if(cnt == 1) {//相当于cnt--,因为cnt==0,result=A[i],cut=1
            result = A[i];
            cnt = 1;
        } else {
            cnt--;
        }
    }
    return result;
}



利用主元素的特性求不知是否有主元素的数组的主元素,复杂度O(n)

在上个程序上进行加工,求出后判断其数量是否占总数50%,是就是主元素,否则无主元素


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


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值