Topic website: https://oj.leetcode.com/problems/single-number/
Title Description:
Given an array of integers, every element appears twice except for one. Find the single one.
Note:
Your algorithm should has a linear runtime complexity. Could you implement it without using extra memory?
Find a number of occurrences only once, O (n) time
Topic Answer:
The initial idea is to sort the array and then pair it from the go, and the difference is that the first number appears once, considering the boundary condition (the array length is 1 or the last number is the number to find)
def singlenumber (self, A): a.sort () If Len (A) = = 1: return a[0] for i in A: if i%2 = = 1: if a[i]! = A[i-1]: return a[i-1] else: pass print "Hey Bitch:" + "a[" + str (i) + "] =" + str (a[i]) + "\ n" el if i = = Len (a): return A[len (a)]
It's a pity that this thing has timed out. Then I thought, List is a super inefficient data structure, why not use Dict, so:
#A. Sort () D = {} for I in A: If I is not in D: d[i] = 1 else: d[i] = d[i]+1 for i in D:
if D[i] = = 1: return I
Space, Time complexity O (n), in fact, sort is not the same sort, but the time complexity of the sort is O (Nlogn). However, the topic said, how to use less or no memory? So:
A.sort () while Len (a)! = 1: A = A.pop () B = A.pop () if A = = B: pass else: return A return A[0]
Use O (1) space, but time went up to O (Nlogn), racked his brains, can't think out AH. So I turned over the comment, there is still a bit operation this thing:
If Len (A) = = 1: return a[0] else: for A in a[1:]: a[0] = a^a[0] return a[0]
This is the solution that really satisfies the problem, even though the code above is over.
Single number | Leetcode OJ Problem Solving report