只出现一次的数字(剑指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
- 只出现一次的数字(剑指offer40)
- 剑指offer40:数组中只出现一次的数字
- 剑指offer40——数组中只出现一次的数字
- 只出现一次的数字
- 剑指offer--数组中只出现一次的数字
- 剑指Offer之 - 数组中只出现一次的数字
- [剑指Offer]40.数组中只出现一次的数字
- 剑指offer-40 数组中只出现一次的数字
- 剑指offer 数组中只出现一次的数字
- 剑指offer 40-数组中只出现一次的数字
- 《剑指offer》数组中只出现一次的数字
- 剑指offer—数组中只出现一次的数字
- 【剑指offer】之数组中只出现一次的数字
- [剑指offer-1351]数组中只出现一次的数字
- 剑指offer:数组中只出现一次的数字
- 剑指offer 40 数组中只出现一次的数字
- 剑指offer:数组中只出现一次的数字
- 剑指offer 数组中只出现一次的数字
- 4.输入一个整数,如果该整数大于1000,则输出“big”,如果该整数介于100到1000之间(包含两个边界),则输出“middle”,如果上面两种情况都不满足,输出”small“
- hwui——Layer的使用
- 梅森旋转算法
- Win8.1使用
- GUI_TestPaintComponent
- 只出现一次的数字(剑指offer40)
- RelativeLayout布局
- 排序算法之三-希尔排序
- HTTP协议的C语言编程实现实例
- VC6.0通过ADO调用SQL Server 2000的存储过程出现参数过多的问题
- maven 入门教程
- nyist 608 畅通工程(并查集)
- hdu 1087 - Super Jumping! Jumping! Jumping!
- 【JAVA学习】java中怎么遍历HashMap(Iterator迭代器遍历)