[LeetCode] 136. Single Number

Description

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

Analyse

一个非空整数数组,有一个元素只出现一次,其他元素都出现两次,找到这个只出现一次的元素

要求线性时间复杂度,不使用额外的内存

(刷知乎的时候刷到“力扣上那些让人虎躯一震的题解”,第一道题就是这个,想起来这道题我看过还没想到怎么做,于是打开LeetCode继续做这个题,还真让我想到了,难怪是道easy题,这篇博客的上部分和下面的部分隔了一个春节)

思路就是使用异或

相同为0
不同为1

nums里所有的数作异或运算得到的就是只出现一次的那个数

2 ^ 2 ^ 1 = 1

同时异或也是支持交换律的

2 ^ 1 ^ 2 = 1

与0异或值不变

2 ^ 0 = 2

最终代码如下

int singleNumber(vector<int>& nums)
{
    int result = nums[0];
    for (int i = 1; i < nums.size(); i++)
    {
        result = result ^ nums[i];
    }
    return result;
}

Result

Runtime: 16 ms, faster than 94.61% of C++ online submissions for Single Number.

Memory Usage: 9.6 MB, less than 100.00% of C++ online submissions for Single Number.

posted @ 2019-02-19 21:56  arcsinW  阅读(117)  评论(0编辑  收藏  举报