最近开始刷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的想法,思路朴实无华,憨憨中透出一丝傻气。
- 创建一个空字典——{},作为散列表
- 遍历nums列表,把列表中每个数作为散列表的key,dict.__contains__(key)用于判断key是否在字典中出现。如果__contains__返回True,表示key已经在字典中,表示当前数字是出现第二次;否则是第一次出现。
- 在字典中遍历所有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中保留仅出现过1次的值
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a