题目
关键词
位运算
思路
- 位运算中的 异或运算(
^) 满足交换律和结合律。 - 性质:
a ^ a = 0(任何数与自身异或结果为0)。a ^ 0 = a(任何数与0异或结果为该数)。
- 因此,将所有数字进行异或运算,成对出现的数字最终会抵消为0,唯一出现一次的数字会被保留下来。
代码
function solution(cards) {
// Edit your code here
let ans = 0
for (let item of cards) {
ans ^= item
}
return ans;
}
function main() {
// Add your test cases here
console.log(solution([1, 1, 2, 2, 3, 3, 4, 5, 5]) === 4);
console.log(solution([0, 1, 0, 1, 2]) === 2);
console.log(solution([0, 1, 0, 1, 3]) === 2);
}
main();
复杂度分析
- 时间复杂度:O(n),其中 n 为数组长度,需要遍历数组中的每一个元素。
- 空间复杂度:O(1),只使用了一个变量
ans进行存储。