[EASY] 136. Single Number

最近开始刷leetcode,由于本菜鸡python使用的不咋样,从EASY题目开始一边刷题一边补习一下python吧。


题目:Single Number

https://leetcode.com/problems/single-number/

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

一个非空数组,所有元素都出现两次,只有一个出现一次,找出只出现一次的那个元素。运行时间要求线性。

我采用了hash的想法,思路朴实无华,憨憨中透出一丝傻气。

  1. 创建一个空字典——{},作为散列表
  2. 遍历nums列表,把列表中每个数作为散列表的key,dict.__contains__(key)用于判断key是否在字典中出现。如果__contains__返回True,表示key已经在字典中,表示当前数字是出现第二次;否则是第一次出现。
  3. 在字典中遍历所有key,返回value等于1的key
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        dicts={}
        for num in nums:
            if dicts.__contains__(num):
                dicts[num]=2
            else:
                dicts[num]=1
        for key in dicts:
            if dicts[key]==1:
                return key

无论多么简单的题,看别人的答案都会觉得醍醐灌顶,记录一下答案里别人精巧的异或操作:

  • a\ \oplus\ 0=a
  • a\ \oplus\ a=0
  • a \oplus b \oplus a=b

异或操作之后,会在变量a中保留仅出现过1次的值

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值