[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.

转载于:https://www.cnblogs.com/arcsinw/p/10403616.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值