leetcode 136、Single Number

Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

两个相同的数异或为0,一个数和0异或不变,因此将所有的数异或即只出现一次的数。

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int ans = 0;
 5         for (int i : nums) {
 6             ans ^= i;
 7         }
 8         return ans;
 9     }
10 };

 

posted @ 2019-01-14 17:56  bloglxc  阅读(76)  评论(0编辑  收藏  举报