只出现一次的数字(剑指offer40)

来源:互联网 发布:网络借贷p2p系统 编辑:程序博客网 时间:2024/05/01 07:10

       问题:一个整型数组里除了一个数字只出现了一次之外,其他的数字都出现了两次。请写程序找出这个只出现一次的数字?如果有两个只出现了一次的数字该如何求解?如果是三个这样的数字时呢?


一、先解答只有一个数字出现了一次的情况

1.暴力穷举法——时间复杂度为O(n^2),空间复杂度为O(1).

int findOnlyNumberWithExhaustion(int* array, int length) {if (NULL == array || 0 >= length || (length & 1)) {std::cerr << "Invalid Parameters." << endl;return -1;}int onlyNumber = 0;for (int i = 0; i < length; ++i) {onlyNumber = array[i];for (int j = 0; j < length && i != j; ++j) {if (onlyNumber == array[j]) {return onlyNumber;}}}return onlyNumber;}

2.先对数组中的数进行排序,然后再查找唯一一个只出现了一次的数字。——时间复杂度为O(n*logn),空间复杂度为O(1).

int findOnlyNumberWithSort(int* array, int length) {if (NULL == array || 0 >= length || (length & 1)) {std::cerr << "Invalid Parameters." << endl;return -1;}//先对数组进行排序mergeSort(array, 0, length - 1);int onlyNumber = 0;for (int i = 0; i < length; i = i + 2) {//第一次出现不相等的两个数的前者就是要找的数if (array[i] != array[i + 1]) {onlyNumber = array[i];break;}}return onlyNumber;}

3.利用异或运算——时间复杂度为O(n),空间复杂度为O(1).

异或操作具有如下的特征:0^num = num; 1^num =~num; num ^ num = 0; 其中num = 0或者1。

int findOnlyNumberWithXOR(int* array, int length) {if (NULL == array || 0 >= length || (length & 1)) {std::cerr << "Invalid Parameters." << endl;return -1;}int xorResult = 0;for (int i = 0; i < length; ++i) {xorResult = xorResult ^ array[i];}int onlyNumber = 0;for (int i = 0; i < length; ++i) {if ((xorResult ^ array[i]) == 0) {onlyNumber = array[i];break;}}return onlyNumber;}

测试代码

#include <iostream>using namespace std;//输入各个数组元素void inputArray(int* array, int length) {for (int i = 0; i < length; ++i) {cin >> array[i];}}int main() {int length = 0;cout << "请输入数组的长度:" << endl;while (cin >> length) {int* x = new int[length];inputArray(x, length);//查找唯一一个只出现了一次的数cout << "唯一元素是:" << findOnlyNumberWithExhaustion(x, length) << endl;cout << "唯一元素是:" << findOnlyNumberWithSort(x, length) << endl;cout << "唯一元素是:" << findOnlyNumberWithXOR(x, length) << endl;delete x;cout << "请输入数组的长度:" << endl;}return 0;}






0 0
原创粉丝点击