Given an 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?算法
給定一個數組,每一個元素都出現2次除了其中的一個,找出只出現一次的數字注意:算法必須是線性時間複雜度,能夠不使用額外空間實現嗎?數組
使用異或運算。app
算法實現類spa
public class Solution { public int singleNumber(int[] nums) { if (nums == null || nums.length < 1) { throw new IllegalArgumentException("nums"); } for (int i = 1; i< nums.length; i++) { nums[0] ^= nums[i]; } return nums[0]; } }