题目
Given a non-empty 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?
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
解析
主要思路:
利用XOR异或运算的运算性质a^0 = a, a^b^b = a, a^b = b^a,对原始数组中的所有数进行异或求和,由于只有待查找数出现1次,而其他数出现2次,因此异或求和的值即为待查找数
代码
class Solution {
public int singleNumber(int[] nums) {
int xorSum = 0;
// 遍历原始数组,进行异或求和
for(int num:nums){
xorSum ^= num;
}
// 返回异或之和
return xorSum;
}
}
推广
类似于这种,求多个数中的某个或某几个特殊数时,可以多尝试使用异或运算的方式进行求解
本文介绍了解决LeetCode 136题“只出现一次的数字”的算法,通过异或运算的特性,在线性时间复杂度内找出数组中唯一出现一次的数字,无需额外内存。

285

被折叠的 条评论
为什么被折叠?



