Cracking code interviews_1
来源:互联网 发布:女友生日送什么花 知乎 编辑:程序博客网 时间:2024/05/29 18:11
题目
数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了一次。请给出最快的方法,找到x。
分析
乍一看这个题目,不少同学立马给出了答案:异或。但举个例子,就会发现,异或是行不通的,一般的方法是利用异或的的如下特性:
A xor A = 0
A xor 0 = A
但是这个题目中,数字都是奇数个的,直接采用之前类似题目的异或方法,已经不合适了。
除此之外,我们还可能想到如下的方法:
采用hashmap,时间复杂度O(n),空间复杂度O(n)
对数组A进行排序,然后在遍历一次,时间复杂度O(nlogn),空间复杂度O(1) 这个方法还可以。
是否还有一些效果更好的方法呢?这一类的题目,即使简单的异或不能解决,也可以从二进制位、位操作方面去考虑,总之这样的大方向是不会错的。
题目中,如果数组中的元素都是三个三个出现的,那么从二进制表示的角度,每个位上的1加起来,应该可以整除3。如果有一个数x只出现一次,会是什么情况呢?
如果某个特定位上的1加起来,可以被3整除,说明对应x的那位是0,因为如果是1,不可能被3整除
如果某个特定位上的1加起来,不可以被3整除,说明对应x的那位是1
根据上面的描述,我们可以开辟一个大小为32的数组,第0个元素表示,A中所有元素的二进制表示的最低位的和,依次类推。最后,再转换为十进制数即可。这里要说明的是,用一个大小为32的整数数组表示,同样空间是O(1)的。
代码如下:
#include <stdio.h>#include <stdlib.h>/** author: grant. alliswell * mail: *****@mail.ustc.edu.cn*/// //////////////////////////////// find one number which only appear once in an array// input: data - an array contains one number appearing only once,// while others appearing exactly third.// length - the length of data// output: num///////////////////////////////////////////////////////////////////////// // set i-th bit in num as 1 void set(int &a, int i){ a |= (1 << i); }// set the i-th in num as 0void clear(int &a, int i){ a &= (~(1 << i));}// find the number apperaing only once in datavoid FindNumAppearOnce(int data[], int length, int &num){ int Bits[32]; for (int i = 0; i < 32; ++i){ Bits[i] = 0; for (int j = 0; j < length; j++){ if (data[j] & (1 << i)) Bits[i] += 1; } } num = 0; for (int i = 0; i < 32; i++) if ((Bits[i] % 3) == 1) set(num, i); }int main(){ int data[16] = {1,1,1,2,2,2,3,3,3,4,4,4,9,10,10,10}; int num = 0; FindNumAppearOnce(data, 16, num); printf("The num appearing only once is: %d", num); return 0;}
1 0
- Cracking code interviews_1
- cracking code interview
- Cracking code interviews_2
- B-Cracking the Code
- zoj 1087 Cracking the Code
- [Information Security] Cracking Vignere Code
- Cracking the code interview总结
- code forces 630 L. Cracking the Code
- Wireless Programming with J2ME: Cracking the Code
- cracking the code interview problem 1.1
- cracking the code interview problem 1.3
- cracking the code interview balanced tree python
- cracking the code interview LCA Python
- CodeForces 630L:Cracking the Code【数论】
- Codeforces 630L Cracking the Code
- WAP, Bluetooth, and 3G Programming: Cracking the Code
- Cracking the code interview 面试题:两个数相加
- Cracking the Code Interview (1): 跟踪数组的中位数
- Android-Creating an Input Method(IME)
- ios程序中的内存分配 栈区堆区全局区
- 关于hbase的一些调优问题
- 带头节点单链表的实现
- 空对象模式
- Cracking code interviews_1
- 黑马程序员--C语言自学笔记---13结构体、预编译、宏、条件编译
- 剑指offer--替换空格
- Java中Runnable和Thread的区别
- AM5728概述(3)
- HDU 2041 超级楼梯(DP)
- C++笔记——多态练习
- Leetcode 7 - Reverse Integer
- 欢迎使用CSDN-markdown编辑器