Topic links
https://leetcode.com/problems/single-number-iii/
Original title
Given An array of numbers nums
, in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. The above example, is
[5, 3]
also correct.
- Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?
Method of Thinking
The topic requires O (1) space complexity and O (n) time complexity, limiting the use of auxiliary structures such as dict, so no longer discuss such solutions.
The topic requires finding two only occurrences of the number once, if done before: 136. Single number, you should be able to think of different or operation.
However, one time or two values can not be obtained, the thought of the final XOR or the resulting value is certainly not 0, then must have at least one bit is 1. According to whether this bit is 1, the original array can be divided into two, respectively, the total XOR of the two dials, the result is the required two number.
In addition, there are many ways to find a binary representation of 1 in a number, and the following two code provides two different methods.
Idea one
Write the code according to the ideas written above.
Code
class solution(object): def singlenumber(self, nums): "" : Type Nums:list[int]: rtype:list[int] "" "res = [0,0] tmp = reduce (Operator.xor, nums) mask = tmp & (-tmp) forIinchNumsifI & mask:res[0] ^= IElse: res[1] ^= IreturnRes
Idea two
Only the XOR of a dial number, and then the total XOR value and the value will be different or can get the other one, reduce a lot of computational amount.
Code
class solution (object) : def singlenumber : res1 = 0 tmp = reduce (Operator.xor, nums) mask = tmp-(TMP & (TMP-1 )) for i in nums: if I & mask:res1 ^= I return [res1, tmp ^ res1]
PS: Write wrong or write not clear please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/52071599
260. Single number III [Medium] (Python)