众数问题

本文介绍了一个用于查找一组字符中出现次数最多的众数及其频率的算法。该算法通过递归方式处理输入的字符向量,利用分治思想找到众数,并记录其最大出现次数。

众数问题

#include <iostream>

#include <vector>

std::vector<char> members;

 

char max_c;//众数

int max_i = 0;//重数

void getMax(std::vector<char>::iterator& start, std::vector<char>::iterator& end) {

    int n = (end - start)/2;

    std::vector<char>::iterator mid = start + n;

    std::vector<char>::iterator l = start, r = end;

    while(*l != *mid && *l != *end){

        l++;

    }

    while(*r != *mid && *r != *start){

        r--;

    }

    start = l;

    end = r;

    if (end – start + 1 > max_i) {

        max_i = end - start + 1;

        max_c = *mid;

    }

}

 

void fun(std::vector<char>::iterator flag, int n){

    std::vector<char>::iterator start = flag;

    std::vector<char>::iterator end = flag + n;

    getMax(start, end);

    int l_count = start - flag;

    int r_count = n - (end - flag);

    if (l_count > max_i){

        fun(flag, l_count);

    }

    if (r_count > max_i) {

        fun(end, r_count);

    }

}

int main() {

    int n;

    std::cout << "input the number of member" << std::endl;

    std::cin >> n;

    for (int i = 0; i < n; i++) {

        char get;

        std::cin >> get;

        members.push_back(get);

    }

    fun(members.begin(), members.size());

    std::cout << max_c << ":" << max_i << std::endl;

    return 0;

}

 

转载于:https://www.cnblogs.com/Anei/p/7828771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值