題目:Given an array of integers, every element appearstwiceexcept for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解題思路:題意為:給定一個數組,只有一個元素出現了一次,其它元素都出現了兩次,找出那個只出現一次的數。可以遍歷數組,分別進行異或運算。
注:異或運算:相同為0,不同為1。遍歷並異或的結果就是那個只出現了一次的數。
示例代碼:
public class Solution { public int singleNumber(int[] nums) { int result=nums[0]; for (int i = 1; i < nums.length; i++) { result^=nums[i]; } return result; } }