众数问题



#include <cstdio>
#include <algorithm>
#include <map>

using namespace std;

bool cmp(const pair<int, int>& p1, const pair<int, int>& p2) {
        return p1.second < p2.second;
}

int main () {
        int t;
        scanf("%d", &t);
        while (t--) {
                map<int, int> m;
                int n;
                scanf("%d", &n);
                for (int i = 0; i < n; ++i) {
                        int ans;
                        scanf("%d", &ans);
                        m[ans]++;
                }

                int num, sum = 0;
                map<int, int>::iterator it = max_element(m.begin(), m.end(), cmp);

                printf("%d %d\n", it -> first, it -> second);
        }
        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
问题是指在一个给定的数组中,出现次数最多的元素称为数。分治法是一种解决问题的思想,它将问题分解成更小的子问题,并通过合并子问题的解来得到原问题的解。下面是使用分治法解决问题的C语言代码示例: ```c #include <stdio.h> // 求解数的函数 int majorityElement(int nums[], int left, int right) { // 当只有一个元素时,直接返回该元素 if (left == right) { return nums[left]; } // 分别求解左右子数组的数 int mid = (left + right) / 2; int leftMajority = majorityElement(nums, left, mid); int rightMajority = majorityElement(nums, mid + 1, right); // 如果左右子数组的数相同,则直接返回该数 if (leftMajority == rightMajority) { return leftMajority; } // 统计左右子数组中数出现的次数 int leftCount = 0, rightCount = 0; for (int i = left; i <= right; i++) { if (nums[i] == leftMajority) { leftCount++; } else if (nums[i] == rightMajority) { rightCount++; } } // 返回出现次数较多的数 return leftCount > rightCount ? leftMajority : rightMajority; } int main() { int nums[] = {1, 2, 2, 2, 3, 4, 2}; int n = sizeof(nums) / sizeof(nums[0]); int result = majorityElement(nums, 0, n - 1); printf("The majority element is: %d\n", result); return 0; } ``` 上述代码中,`majorityElement`函数使用递归的方式将数组分解成更小的子数组,并分别求解左右子数组的数。然后通过统计左右子数组中数出现的次数,返回出现次数较多的数。在`main`函数中,我们定义了一个示例数组`nums`,并调用`majorityElement`函数来求解数。最后将结果打印输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值