题目描述(Medium)
Given a non-empty 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?
题目链接
https://leetcode.com/problems/single-number-ii/description/
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
算法分析
创建一个长度为sizeof(int)的数组count[sizeof(int)],count[i]表示在i位出现的1的次数。如果count[i]是3的整数倍,则忽略;否则就把该位取出来组成答案,时间复杂度为
,空间复杂度
。
提交代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
const int W = 8 * sizeof(int);
int count[W];
fill_n(count, W, 0);
for (int i = 0; i < nums.size(); ++i)
{
for (int j = 0; j < W; ++j)
{
count[j] += (nums[i] >> j) & 0x1;
count[j] %= 3;
}
}
int result = 0;
for (int i = 0; i < W; ++i)
result += (count[i] << i);
return result;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, int expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName);
Solution s;
int result = s.singleNumber(nums);
if (result == expected)
printf("passed\n");
else
printf("failed\n");
}
int main(int argc, char* argv[])
{
vector<int> ratings = { 2, 2, 3, 2 };
Test("Test1", ratings, 3);
ratings = { 0, 1, 0, 1, 0, 1, 99 };
Test("Test2", ratings, 99);
return 0;
}