首页 > 其他 > 详细

查找过半元素(SOJ 4389)

时间:2019-03-01 13:30:05      阅读:138      评论:0      收藏:0      [点我收藏+]

SOJ 4389: http://acm.scu.edu.cn/soj/problem.action?id=4389

题意非常简单:给定一个数组,找出过半的那个元素。刚开始我考虑从中位数入手,因为中位数一定是所求的答案。所以,利用快排找第(n+1)/2个元素,结果超时了。后来参考了别人的算法,这道题是有O(n)的算法的。核心思想是:两个不相等的数抵消,最后一定可以剩下过半的元素。看了别人的代码,有开数组的,有用队列的,实际上都不必。

代码如下:

技术分享图片
#include<iostream>
using namespace std;
int main()
{
    int T;
    scanf("%d", &T);
    int n;
    int i;
    int result;
    int temp;
    int count;
    while (T--)
    {
        scanf("%d", &n);
        count = 0;
        for (i = 0; i < n; i++)
        {
            scanf("%d", &temp);
            if (count == 0)
            {
                result = temp;
                count++;
            }
            else
            {
                if (temp == result)
                    count++;
                else
                    count--;
            }
        }
        printf("%d\n", result);
    }
    return 0;
}
View Code

参考以下博文:

https://blog.csdn.net/computer_liuyun/article/details/42062223

https://www.cnblogs.com/87hbteo/p/7146007.html

查找过半元素(SOJ 4389)

原文:https://www.cnblogs.com/ClearMoonlight/p/10455817.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!