题目链接:
https://leetcode.com/problems/single-number/description/
描述
Given an 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?
输入
输入一串数字,只有一个数的个数是1,其他数的个数均为2,找出这个个数为1的数。要求:算法不能申请额外内存且时间复杂度为线性。
输出
数组中个数为1的数
样例输入
[5,2,2,,3,3,4,4] |
样例输出
5 |
算法思想:
使用异或操作符来解决。A xor A = 0,0 oxr A = A,故将0与数组中的所有数均异或一次,得到的结果就是数组中仅出现过一次的数。
源代码
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for (int i = 0; i<n; i++)
{
result ^=A[i];
}
return result;
}
};
算法复杂度:
一次循环,故时间复杂度为O(n),只申请常量大小的内存,故符合题目要求。