leetcode python3 简单题136. Single Number

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第一百三十六题

(1)题目
英文:
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?

中文:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number

(2)解法
① 使用现成的方法
(耗时:40ms,内存:15.3M)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        datas = collections.Counter(nums)
        for each in datas:
            if datas[each] == 1: return each

注意:
1.collections.Counter(nums)输出的是{}字典类型,key为元素,value为元素重复的次数。
2.for each in datas中的each是每个key。

② 切片操作
(耗时:5372ms,内存:15.6M)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        for i in range(len(nums)):
            if nums[i] not in nums[0:i] and nums[i] not in nums[i+1:]: return nums[i]

③ 异或
(耗时:48ms,内存:15.3M)

class Solution(object):
     def singleNumber(self, nums: List[int]) -> int:
        a = 0
        for i in nums:
            a ^= i
        return a

注意:
1.任何数与0异或都是原数。
2.两个相同的数异或是0。
3.对于连个数的异或要转换成二进制来位运算哦!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值