1 single number
Given an array of integers, every element appearsTwiceCould t for one. Find that single one.
Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?
Resolution:
A ^ A = 0, a ^ 0 =
Therefore, the final result is the difference or for all numbers.
1 public int singleNumber(int[] A) {2 int single = 0;3 for (int i : A) {4 single ^= i;5 }6 return single;7 }
View code2 single number II
Given an array of integers, every element appearsThreeTimes has t for one. Find that single one.
Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?
Resolution:
(1) A @ A = 0, a @ 0 =
You only need to find the operation function @ that satisfies the preceding equation.
(2) A-> one, a @ A-> two, a @ A-> One @ two = 0
That is, if operation a is performed, the result is recorded to one. If operation two times, the result is recorded to two. If operation three times, the result is recorded to one and two, and the result is set to 0.
1 public int singleNumber_3(int[] A) { 2 int one = 0; 3 int two = 0; 4 for (int carry : A) { 5 while (carry != 0) { 6 two ^= one & carry; 7 one ^= carry; 8 carry = one & two; 9 }10 }11 return one;12 }
View code
Single Number and single number II