Single Number
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?
解调思路:考察异或的概念。 在二进制表示中, 异或操作的结果是每一位相同为1,不同为0. 题目的描述是除了有一个数只出现了一次之外,其余的数都出现了两次。因此对数组进行异或操作,那么剩下来的数就是那个只出现了一次的数。
1 public class Solution { 2 public int singleNumber(int[] nums) { 3 int ans = 0; 4 for (int i = 0; i < nums.length; i++) { 5 ans ^= nums[i]; 6 } 7 return ans; 8 } 9 }

浙公网安备 33010602011771号