Answer: Take use of bitwise XOR, because only when number XOR with itself, result would be 0. Thus, the result of whole array XOR should be that single number
class Solution { public int singleNumber(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int singleNumber = 0; for (int i = 0; i < nums.length ; i ++) { singleNumber ^= nums[i]; } return singleNumber; } }
No comments:
Post a Comment