题意
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
解
a ^ b ^ b = a
根据异或运算的性质可知,把所有元素参与异或运算,即得到答案。
// Runtime: 1 ms, faster than 74.06% of Java online submissions for Single Number.
//Memory Usage: 39.3 MB, less than 6.29% of Java online submissions for Single Number.
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int rst = nums[0];
for (int i = 1; i < nums.length; i++)
rst ^= nums[i];
return rst;
}
本文地址:https://blog.csdn.net/he25819/article/details/109244139