您的位置:首页 > 编程语言 > C语言/C++

LeetCode 136. Single Number

2017-03-21 16:08 411 查看

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?

Analysis

XOR is used to find the single letter because the twice appearance of other letters.

(A⊕B)⊕(A⊕B⊕C)=0⊕C=C

Code

class Solution {
public:
int singleNumber(vector<int>& nums) {
int single = 0;
for(int n : nums)  single ^= n;
return single;
}
};


Appendix

Link:https://leetcode.com/problems/single-number/

Run Time: 13ms

New grammar in C++11 called Interval traversal performs better.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 cpp bit