hdoj2095 find your present (2)

题目:

Problem Description
In the new year party, everybody will get a "special present".Now it's your turn to get your special present, a lot of presents now putting on the desk, and only one of them will be yours.Each present has a card number on it, and your present's card number will be the one that different from all the others, and you can assume that only one number appear odd times.For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1.so your present will be the one with the card number of 3, because 3 is the number that different from all the others.
Input
The input file will consist of several cases. Each case will be presented by an integer n (1<=n<1000000, and n is odd) at first. Following that, n positive integers will be given in a line, all integers will smaller than 2^31. These numbers indicate the card numbers of the presents.n = 0 ends the input.
Output
For each case, output an integer in a line, which is the card number of your present.
Sample Input
51 1 3 2 231 2 10
Sample Output
32
Hint
Hint

  • *use scanf to avoid Time Limit Exceeded

题目大意: 给你一组奇数个序列,每个序列中有一个数与其他数都不相同( 其他数会出现多次)。找出这个数。

这题可以先对序列进行排序,在比较这个数和前后两个数是否相等,若没有找到则考虑第一个元素和最后一个元素即可。

参考代码:

#include 
#include 
#include 
using namespace std;
const int N = 1000000+10;

int a[N];

void init() {
    memset(a, 0, sizeof(a));
}

void input(int n) {
    for (int i = 0;i < n;++i) {
        cin >> a[i];
    }
}

int diffnum(int n) {
    sort(a, a + n);
    int ans = 0;
    for (int i = 0;i < n;++i) {
        if ((i-1 >= 0 && i+1 < n && a[i] != a[i-1] && a[i] != a[i+1]) || 
                (i == 0 && i+1 < n && a[i] != a[i+1]) || (i == n-1 && 
                    a[i] != a[i-1])) {
            ans = a[i];
            break;
        }
    }
    return ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    while (cin >> n) {
        if (n == 0) break;
        init();
        input(n);
        int ans = diffnum(n);
        cout << ans << endl;
    }
    return 0;
}

但这道题还有一个奇怪的地方,就是最后的结果一定是这个序列里面最大的那个数。

#include 
#include 
#include 
using namespace std;
const int N = 1000000+10;

int a[N];

void init() {
    memset(a, 0, sizeof(a));
}

void input(int n) {
    for (int i = 0;i < n;++i) {
        cin >> a[i];
    }
}

int diffnum(int n) {
    sort(a, a + n);
    return a[n-1];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    while (cin >> n) {
        if (n == 0) break;
        init();
        input(n);
        int ans = diffnum(n);
        cout << ans << endl;
    }
    return 0;
}

你可能感兴趣的:(hdoj2095 find your present (2))