136. Single Number

来源:互联网 发布:sql case when 嵌套 编辑:程序博客网 时间:2024/06/03 04:46

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?


官方解答如下:

Solution


Approach #1 List operation [Time Limit Exceeded]

Algorithm

  1. Iterate over all the elements in nums\text{nums}nums
  2. If some number in nums\text{nums}nums is new to array, append it
  3. If some number is already in the array, remove it

Python

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        no_duplicate_list = []        for i in nums:            if i not in no_duplicate_list:                no_duplicate_list.append(i)            else:                no_duplicate_list.remove(i)        return no_duplicate_list.pop()

Complexity Analysis

  • Time complexity : O(n2)O(n^2)O(n2). We iterate through nums\text{nums}nums, taking O(n)O(n)O(n) time. We search the whole list to find whether there is duplicate number, takingO(n)O(n)O(n) time. Because search is in the for loop, so we have to multiply both time complexities which isO(n2)O(n^2)O(n2).

  • Space complexity : O(n)O(n)O(n). We need a list of size nnn to contain elements in nums\text{nums}nums.


Approach #2 Hash Table [Accepted]

Algorithm

We use hash table to avoid the O(n)O(n)O(n) time required for searching the elements.

  1. Iterate through all elements in nums\text{nums}nums
  2. Try if hash_tablehash\_tablehash_table has the key for pop
  3. If not, set up key/value pair
  4. In the end, there is only one element in hash_tablehash\_tablehash_table, so use popitem to get it

Python

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)O(n * 1) = O(n)O(n1)=O(n). Time complexity of for loop is O(n)O(n)O(n). Time complexity of hash table(dictionary in python) operation pop isO(1)O(1)O(1).

  • Space complexity : O(n)O(n)O(n). The space required by hash_tablehash\_tablehash_table is equal to the number of elements in nums\text{nums}nums.


Approach #3 Math [Accepted]

Concept

2∗(a+b+c)−(a+a+b+b+c)=c2 * (a + b + c) - (a + a + b + b + c) = c2(a+b+c)(a+a+b+b+c)=c

Python

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        return 2 * sum(set(nums)) - sum(nums)

Complexity Analysis

  • Time complexity : O(n+n)=O(n)O(n + n) = O(n)O(n+n)=O(n).sum will call next to iterate through nums\text{nums}nums.We can see it as sum(list(i, for i in nums)) which means the time complexity isO(n)O(n)O(n) because of the number of elements(nnn) in nums\text{nums}nums.

  • Space complexity : O(n+n)=O(n)O(n + n) = O(n)O(n+n)=O(n).set needs space for the elements in nums


Approach #4 Bit Manipulation [Accepted]

Concept

  • If we take XOR of zero and some bit, it will return that bit
    • a⊕0=aa \oplus 0 = aa0=a
  • If we take XOR of two same bits, it will return 0
    • a⊕a=0a \oplus a = 0aa=0
  • a⊕b⊕a=(a⊕a)⊕b=0⊕b=ba \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = baba=(aa)b=0b=b

So we can XOR all bits together to find the unique number.

Python

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

Complexity Analysis

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

  • Space complexity : O(1)O(1)O(1).


Analysis written by: @Ambition_Wang


java实现的版本如下:

import java.util.HashMap;
import java.util.HashSet;

public class SingleNumber {
    //set version
    public int singleNumber_set(int[] nums) {
        HashSet<Integer> hashSet=new HashSet<>();
        int sum=0;
        for(int i=0;i<nums.length;i++)
        {
            hashSet.add(nums[i]);
            sum+=nums[i];
        }
        int sum1=0;
        for(int num:hashSet)
        {
            sum1+=num;
        }
        return 2*sum1-sum;
    }
    //hashmap version
    public int singleNumber_hashmap(int[] nums) {
        HashMap<Integer, Integer> hashMap=new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++)
        {
            if(hashMap.containsKey(nums[i]))
            {
                hashMap.remove(nums[i]);
            }
            else
            {
                hashMap.put(nums[i], 0);
            }
        }
        for(Integer key:hashMap.keySet())
        {
            return key;
        }
        return -1;
    }
    //bit manipulation version
    public int singleNumber(int[] nums) {
        int answer=nums[0];
        for(int i=1;i<nums.length;i++)
        {
            answer^=nums[i];
        }
        return answer;
        
    }
}

类似的还有

389. Find the Difference


原创粉丝点击