leetcode 136. Single Number

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?

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

Concept

If we take XOR of zero and some bit, it will return that bit
a⊕0=a
If we take XOR of two same bits, it will return 0
a⊕a=0
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
So we can XOR all bits together to find the unique number.

Complexity Analysis:

Time complexity : O(n). We only iterate through nums, so the time complexity is the number of elements in nums.

Space complexity : O(1).

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        hash_table = {}
        for i in nums:
            try:
                hash_table.pop(i)
            except:
                hash_table[i] = 1
        return hash_table.popitem()[0]

Complexity Analysis:

Time complexity : O(n∗1)=O(n). Time complexity of for loop is O(n). Time complexity of hash table(dictionary in python) operation pop is O(1).

Space complexity : O(n). The space required by hash_table is equal to the number of elements in nums

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 忘掉小话心境宽,宽恕自己也是宽容别人,少一点计较,多一点理解,这个世界会比我们现在所看到的更美好一些! ...
    浮生如梦的幸福时光5376阅读 2,839评论 0 0
  • 遗忘通常是件不能选择的事。 几年前,我相信自己是个念旧的人。喜欢怀念,越是远的记忆越是清晰。如小学每夜陪我等麻麻的...
    远行灯阅读 1,571评论 0 0
  • 张爱玲对爱情说过的七句话 人总要在磕磕绊绊中才能学会成长,遇到错的人是想让你在遇到对的人的时候,心怀感激并懂得了如...
    54谭小姐阅读 3,669评论 0 1
  • 9月7日 几个心情忘记记录… 9月8日 心情1,晚上画画线描课上画了小蜗牛,一开始忘记怎么画,后来慢慢画好了,感觉...
    sophiawyl阅读 1,274评论 0 0

友情链接更多精彩内容