Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once. Explanation:
Your algorithm should have linear time complexity. Can you do it without using extra space?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
public int singleNumber(int[] nums) {
int num = 0;
for(int i = 0; i < nums.length; i++){
num = num ^ nums[i];
}
return num;
}
Time complexity: O(n)
Space complexity: O(n)