题目描述(Easy)
Given a non-empty array of integers, every element appears twice except for one. 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/description/
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
算法分析
异或操作去除偶数次的数字,时间复杂度
,空间复杂度
。
提交代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = nums[0];
for (int i = 1; i < nums.size(); ++i)
result ^= nums[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, 1};
Test("Test1", ratings, 1);
ratings = { 4, 1, 2, 1, 2 };
Test("Test2", ratings, 4);
return 0;
}