Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Idea: Bit manipulation. Only the target shows up once, the other elements show up twice. Therefore use exclusive or (XOR) to clean the interference of other elements.
Time: O(n). Space: O(1).
Code:
public class Solution {
public int singleNumber(int[] A) {
int res=0;
for(int i:A)
{
res=res^i;
}
return res;
}
}
No comments:
Post a Comment