Leetcode-Single Number

Posted by Xiaoye's Blog on March 21, 2020

Problem

Leetcode problems:

  1. 136 sinlge number
  2. 137 single number II
  3. 260 single num III

Solution

There are two aprroches to solve these problems

  1. Hash table: hash table is a very important tool to solve problem related to array. dict in Python is implemented with hash table.
  2. Bit manipulation: not so clear about this approach, I’ll add these part latter

Hash Table

Take 137 as an example, solutions are as follows:

from typing import List


class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        common_time = 3
        special_time = 1
        result_dict = {}
        for n in nums:
            try:
                result_dict[n] += 1
                if result_dict[n] == common_time:
                    del result_dict[n]
            except:
                result_dict[n] = 1
        return list(result_dict.keys())[0]

Bit Manipulation

I’ll cover the approach latter.