您的位置:首页 > 其它

[Leetcode] Single Number

2016-12-18 21:51 302 查看

描述

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?

分析

这道题跟 Missing Number 的第二种做法很像,直接对所有数进行异或,时间复杂度 O(n) ,空间复杂度 O(1) ,代码如下。

代码

class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (int i:nums) res = res ^ i;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: