HDU1029 Ignatius and the Princess IV

问题链接:HDU1029 Ignatius and the Princess IV。基础练习题,用C++语言编写。

题意简述:输入n(n是奇数),然后输入n个整数,求出现(n+1)/2次的整数。

问题分析:n是奇数,(n+1)/2是n的一半以上,只要将n个数据排序,出现(n+1)/2次的整数必然会出现在中间位置。

本问题使用C++语言编写的原因是函数sort()的参数简单,使用方便。

AC的C++语言程序如下:

/* HDU1029 Ignatius and the Princess IV */

#include <iostream>
#include <algorithm>

using namespace std;

const int MAXN = 999999;
int data[MAXN];

int main()
{
    int n;

    while(cin >> n) {
        for(int i=0; i<n; i++)
            cin >> data[i];

        sort(data, data + n);

        printf("%d
", data[(n + 1) / 2]);
    }

    return 0;
}


原文地址:https://www.cnblogs.com/tigerisland/p/7564443.html