Given an array of integers, every element appears three times except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
链接:http://oj.leetcode.com/problems/single-number-ii/
问题:给一个数组,里面只有一个数字一次,其它数字都出现3次,找出这个出现一次的数字,要求时间复杂度为O(n),空间复杂度为O(1)。
例子:
1
Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
可以通过排序在O(nlogn)的时间内解决,也可以用hash,但是最坏的情况下复杂度可能会超过O(n),hash需要的空间复杂度也比较大。
前面的Single Number[位运算] 是一个很简单的位运算题目。
这里的思想是还是位运算的方法解决。并不是简单的异或等操作,因为所有的数字都是出现奇数次 。大家可以先参考careercup上面的这个面试题 。
这里我们需要重新思考,计算机是怎么存储数字的。考虑全部用二进制表示,如果我们把 第 ith 个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0). 因此取余的结果就是那个 “Single Number”.
一个直接的实现就是用大小为 32的数组来记录所有 位上的和。
01
int
singleNumber(
int
A[],
int
n) {
04
for
(
int
i = 0; i < 32; i++) {
05
for
(
int
j = 0; j < n; j++) {
06
if
((A[j] >> i) & 1) {
10
result |= ((count[i] % 3) << i);
这个算法是有改进的空间的,可以使用掩码变量:
ones
代表第ith 位只出现一次的掩码变量 twos
代表第ith 位只出现两次次的掩码变量 threes
代表第ith 位只出现三次的掩码变量
假设在数组的开头连续出现3次5,则变化如下:
当第 ith 位出现3次时,我们就 ones
和 twos
的第 ith 位设置为0. 最终的答案就是 ones。
01
int
singleNumber(
int
A[],
int
n) {
02
int
ones = 0, twos = 0, threes = 0;
03
for
(
int
i = 0; i < n; i++) {
参考:http://oj.leetcode.com/discuss/857/constant-space-solution
转自:http://www.acmerblog.com/leetcode-single-number-ii-5394.html