Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
1 /*Time: O(n), Space: O(1) 2 exclusive or operation: 3 1 XOR 1 = 0 4 1 XOR 0 = 1 5 0 XOR 1 = 1 6 0 XOR 0 = 0 7 0 XOR A = A 关键:0异或任何数还是任何数 8 */ 9 public int singleNumber(int[] nums) { 10 if (nums == null || nums.length == 0) { 11 return 0; 12 } 13 14 int result = 0; 15 16 for (int i = 0; i < nums.length; i++) { 17 result = result ^ nums[i]; 18 } 19 20 return result; 21 }