Q: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?
思路:一个整数异或它本身,结果为0. 所以只要遍历一次数组即可得到只出现一次的数字.
代码:
public int singleNumber(int[] nums) {
int length = nums.length, i = 0;
long sum = 0L;
while (i < length) {
sum ^= nums[i++];
}
return (int) sum;
}
寻找唯一元素

本文介绍了一种线性时间复杂度的算法来找出数组中仅出现一次的整数。该方法利用了整数异或运算的特性,通过遍历数组并进行异或操作找到目标元素,且不使用额外内存。
5232

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



