开个贴记录leetcode刷题,每天刷五道easy,刷完后刷medium,用python和c++做。今天第一天,加油!
题目
原题
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?
翻译
给定一个数组,里面全是整数,每个数字都重复两遍,只有一个没有重复,找到那个不重复的数字。
注意:时间复杂度为线性,并且不占用额外内存。
链接
方法
我的方法
from collections import Counter
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return [k for k,v in Counter(nums).items() if v == 1]
if __name__==‘__main__‘:
print Solution().singleNumber([1,1,2,2,3])
输出结果
3
结果
Wrong Answer
正确答案
import operator
class Solution:
"""
:type nums: List[int]
:rtype: int
"""
def singleNumber(self, A):
return reduce(operator.xor, A)
if __name__ == ‘__main__‘:
print Solution().singleNumber([1, 1, 2, 2, 3])
感想
一开始疑惑为啥错了,后来放到一起比较后,发现正确答案输出的是int 3,我输出的list [3],后来在return后面加上了取出这个list的值,结果就对了,但是运行速度很慢,对比一下:
- 我的答案:You are here! Your runtime beats 14.20 % of python submissions.
- github答案:You are here! Your runtime beats 66.96 % of python submissions.
为啥我的答案要慢这么多呢?留个坑想想