Single Number
My SubmissionsGiven 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?
思路:两个相同的数异或之后的值为零,那么该题将n个数异或,得到的就是那个single one~
class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (A == 0 || n < 1)
return 0;
int key = A[0];
for (int i = 1; i < n; ++i) {
key ^= A[i];
}
return key;
}
};

本文介绍了解决数组中每个元素出现两次但有一个元素仅出现一次的问题,通过使用异或运算来找到那个唯一出现的元素,同时强调了算法的时间复杂度为线性。
1440

被折叠的 条评论
为什么被折叠?



