列表

详情


XM19. 一组带数字编号的球,其中有两个编号只出现了一次,把它们找出来

描述

一组带数字编号的球里除了两个编号之外,其它的编号都出现了两次。
请写程序找出这两个只出现一次的编号。要求时间复杂度是O(n),空间复杂度是O(1)。

输入描述

整形数组
长度不超过1000000

输出描述

输出数组中2个只出现了一次的数
先输出较小的数

示例1

输入:

1
2
3
4
5
2
3
4
5
6

输出:

1 6

原站题解

C++ 解法, 执行用时: 91ms, 内存消耗: 4216KB, 提交时间: 2020-12-21

#include <iostream>
using namespace std;
      
int main() {
    ios::sync_with_stdio(false);
    int arr[1000000];
    int n = 0;
    while (cin >> arr[n]) { ++n; }
    int res = 0;
    for(int i=0; i < n; ++i) {
        res ^= arr[i];
    }
    int k = 0;
    while ((res & 1) == 0) {
        res >>= 1;
        ++k;
    }
    int ans1 = 0, ans2 = 0;
    for (int i=0; i < n; ++i) {
        if ((arr[i]>>k) & 1) {
            ans1 ^= arr[i];
        }else {
            ans2 ^= arr[i];
        }
    }
    if (ans1 <= ans2) { cout << ans1 << " " << ans2; }
    else { cout << ans2 << " " << ans1; }
    return 0;
}

C++ 解法, 执行用时: 91ms, 内存消耗: 4224KB, 提交时间: 2020-10-29

#include <iostream>
using namespace std;
      
int main() {
    ios::sync_with_stdio(false);
    int arr[1000000];
    int n = 0;
    while (cin >> arr[n]) { ++n; }
    int res = 0;
    for(int i=0; i < n; ++i) {
        res ^= arr[i];
    }
    int k = 0;
    while ((res & 1) == 0) {
        res >>= 1;
        ++k;
    }
    int ans1 = 0, ans2 = 0;
    for (int i=0; i < n; ++i) {
        if ((arr[i]>>k) & 1) {
            ans1 ^= arr[i];
        }else {
            ans2 ^= arr[i];
        }
    }
    if (ans1 <= ans2) { cout << ans1 << " " << ans2; }
    else { cout << ans2 << " " << ans1; }
    return 0;
}

上一题