Given an array of integers, every element appears twice except for one. Find that single one.app
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?code
Solutionip
public int singleNumber(int[] nums) { int re = 0; for(int i=0; i< nums.length; i++ ){ re ^= nums[i]; } return re; }
這裏使用異或的方法。 好比輸入的數組是 {1, 2, 3, 4, 2, 3, 1}element
re = 0^1^2^3^4^2^3^1 =0^(1^1)^(2^2)^(3^3)^4 =0^0^0^0^4 =0^4 =4