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]
.
Title: To an array, the array has the same elements, there are different elements, each group of the same element just two, different elements are just two
Train of thought: 1, before the condition that did not seriously see the topic, led to write a set of common, no matter how many of the same element, code optimization is as follows:
Public int[] Singlenumber (int[] nums) {
int len = nums.length;
map<integer,integer> Countmap = new hashmap<integer,integer> ();
for (int i = 0;i<len;i++) {
Integer count = Countmap.get (Nums[i]);
if (count==null) {
Countmap.put (nums[i],1);
}else{
Countmap.put (nums[i],count+1);
}
}
int[] res = new INT[2];
int i = 0;
For (Entry E:countmap.entryset ()) {
if ((Integer) E.getvalue () ==1) {
res[i++] = (Integer) e.getkey ();
}
}
return res;
}
More in line with test instructions's ideas 2:
Thinking 2 is mainly based on the characteristics of the logic bit operation: Because test instructions is the number of the same elements in each group only two, then we just have to make them XOR or the operation of a bit, it is 0, the array of all the number of different or operation, and finally get the results of two distinct elements Can be based on the results of the second binary form of one of the 1, why go to 1, because the XOR operation is the same as 0, the difference is 1, this can be differentiated two different numbers, differentiated out, over ...
Public int[] Singlenumber (int[] nums) {
int distinct = 0,len = Nums.length;
for (int i = 0;i <len;i++) {
Distinct ^= nums[i];
}
Distinct &=-distinct;
int res [] = new int[2];
for (int i = 0;i<len;i++) {
if ((Res&nums[i]) ==0) {
Res[0] ^=nums[i];
}else{
Res[1]^=nums[i];
}
}
return res;
}
Runtime incredibly 2ms, than I before that is much faster, to tell the truth, this problem let me feel the programming of happiness
leetcode| Single number III