[LeetCode]Single Number

本文介绍使用Python解决LeetCode中寻找数组中唯一出现一次的元素的问题,提供了两种解决方案,一种是利用字典记录每个元素出现的次数,另一种是使用XOR操作实现线性时间和常数空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

重新开始刷题,最近工作中都用python,就改用python写吧,从些简单的开始~LOL

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?


1st Solution:

Running Time: O(n), 

Extra Space: O(n)

create a dictionary to record each number's frequency of occurrence.

class Solution():
    def singleNumber(self, A):
        dict = {}
        for item in A:
            if item in dict.keys():
                dict[item] += 1
            else:
                dict[item] = 1
        for n in dict.keys():
            if dict[n] == 1:
                return n
由于创建了额外的空间(dict), 1st solution 无法通过OJ.


2nd Solution:

Running Time: O(n)

Extra Space: none

Use XOR(Exclusive OR)

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        return reduce(lambda x,y:x^y, A)
区区一行代码,不得不感慨python的简洁精炼。


Reference:

(XOR): x ^ y, which does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.

Python lambda functions





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值