Given An array of numbers nums, in which exactly, elements appear only once and all the other elements appear exactly t Wice. 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?
Thinking of solving problems
Bit operations. The difference from the single number is that the first one is grouped according to whether or not either of the elements or the result is 1, and then the single number in each group is found separately.
Implementation code
Java:
//Runtime:2 MS Public classSolution { Public int[]Singlenumber(int[] nums) {intXOR =0; for(intNum:nums) {xor ^= num; }intbit = XOR & (~ (XOR-1));intSingle[] =New int[2]; for(intNum:nums) {if(num & bit)! =0) {single[0] ^= num; }Else{single[1] ^= num; } }returnSingle }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Single number III