描述
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
- 思路
这道题需要时间复杂度为n,空间复杂度为常量C,按照常规思路很难实现。看了其他博主的思路,才明白这里需要使用位操作去实现,思路可以看:
http://blog.csdn.net/feliciafay/article/details/19004479;
https://www.cnblogs.com/yanliang12138/p/4536189.html;
下面给出c#代码 - 代码(c#)
public int SingleNumber(int[] nums) {
int[] count = new int[32];
int result = 0;
for (int i = 0; i < 32; i++)
{
for (int j = 0; j < nums.Length; j++)
{
count[i] += ((nums[j] >> i) & 1); //首先把输入数字的第i位加起来。
count[i] = count[i] % 3; //然后求它们除以3的余数。
}
result |= (count[i] << i);//把二进制表示的结果转化为十进制表示的结果
}
return result;
}
- 不符合题目要求的思路
这里可以先对给出的数组进行排序,在排序后对数据进行判断就方便了许多。这种思路的时间复杂度为nlogn,空间复杂度为C,在LeetCode上面可以ac通过。 - 代码(c#)
public int SingleNumber(int[] nums) {
nums = nums.OrderBy(x => x).ToArray();//进行排序
for (int i = 2; i < nums.Length; i = i + 3)
{
if (nums[i - 2] != nums[i]) return nums[i-2];//找到了只出现了一次的数字
}
return nums[nums.Length - 1];//最后一个数字一定是只出现了一次的数字
}