Topic:
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?
Ideas:
Related Topics:
Leetcode OJ Single number (unique digit)
Leetcode OJ Single number II (unique digit-two)
Reference: http://blog.csdn.net/u012243115/article/details/45286963.
Code:
Class Solution {public:vector<int> Singlenumber (vector<int>& nums) {vector<int> ResU Lt int len = Nums.size (); if (Len < 2) return result; int tmp = 0; for (int i = 0; i < len; i++) tmp ^= nums[i]; int indexofone = 0; for (int i = 0; i <; i++) {if (TMP & (1 << i)! = 0)//NOTE: bit operator & has a low priority, plus (). It is better to use 1 for the shift operation than for the TMP, because if the TMP is negative, the right side will be 1. (although this does not affect the result, it is best not to do a shift operation on tmp) {indexofone = i; Break }} int tmp2 = (1 << indexofone); int NUM1 = 0, num2 = 0; for (int i = 0; i < len; i++) {if (Nums[i] & tmp2) num1 ^= nums[i]; else num2 ^= Nums[i]; } result.push_back (NUM1); Result.push_back (NUM2); return result; }};
Copyright NOTICE: Reprint please indicate the source.
Leetcode OJ Single number III (unique digit-three)