美文网首页
[leetcode]136. Single Number

[leetcode]136. Single Number

作者: SQUA2E | 来源:发表于2019-07-27 15:14 被阅读0次

题目

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Input: [2,2,1]
Output: 1

分析

题目是找出列表中只出现一次的数。其他数均出现两次。
初始话一个字典用来储存出现次数。最后找到dic.value为1的`dic.key.

代码values

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        dic={e:2 for e in nums}
        for e in nums:
            dic[e] -= 1
        return list(dic.keys())[list(dic.values()).index(1)]

list(dic.keys())list(dic.values())分别返回key 和 value的列表

相关文章

网友评论

      本文标题:[leetcode]136. Single Number

      本文链接:https://www.haomeiwen.com/subject/ghkerctx.html