Write a record Leetcode brush questions, brush Five easy every day, brush medium after brushing, with Python and C + + do. The first day today, come on!
Title Original question
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?
Translation
给定一个数组,里面全是整数,每个数字都重复两遍,只有一个没有重复,找到那个不重复的数字。注意:时间复杂度为线性,并且不占用额外内存。
Link
Method of my method
from collections import Counterclass solution (object ): def Singlenumber (self , Nums): "" " : Type Nums:l Ist[int] : Rtype:int retu RN [k for k,v in Counter (nums). Items () if v == 1 ]if __name_ _ == ' __main__ ' : print solution (). Singlenumber ([1 , 1 , 2 , 2 , 3 ])
Output results
3
Results
Wrong Answer
Correct answer
import operatorclass Solution: """ :type nums: List[int] :rtype: int """ def singleNumber(self, A): returnreduce(operator.xor, A)if__name__==‘__main__‘: print Solution().singleNumber([11223])
Feelings
一开始疑惑为啥错了,后来放到一起比较后,发现正确答案输出的是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.为啥我的答案要慢这么多呢?留个坑想想
"Leetcode" Day1 Singular number (python)