[NeetCode 150] Single Number

Single Number

You are given a non-empty array of integers nums. Every integer appears twice except for one.

Return the integer that appears only once.

You must implement a solution with O(n)O(n)O(n) runtime complexity and use only O(1)O(1)O(1) extra space.

Example 1:

Input: nums = [3,2,3]

Output: 2

Example 2:

Input: nums = [7,6,6,7,8]

Output: 8

Constraints:

1 <= nums.length <= 10000
-10000 <= nums[i] <= 10000

Solution

The key idea of this problem is to find an operation that can transform 2 identical numbers into a constant, while when the constant is operated with another number, the value of the number doesn’t change.

Operation XOR ⊕\oplus has such properties that
a⊕a=00⊕a=a a \oplus a = 0\\ 0 \oplus a = a aa=00a=a
When XOR operation is applied to the whole list, each identical number pair will cancel each other. Therefore, the remaining number with be the only single one.

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ans = 0
        for num in nums:
            ans ^= num
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值