Leetcode_136_Single Number

时间:2023-03-10 00:07:30
Leetcode_136_Single Number

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.****.net/pistolove/article/details/42713315



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)题意为给定一个整形数组,其中数组中除了一个元素之外,其它任意元素都出现两次,求只出现一次的元素。

(2)由于题目限制了时间复杂度为线性的,即不能出现多次for循环,且建议最好不要申请额外的空间。这样,我们就需要思考,如何在遍历数组一次的情况下找出出现一次的元素。考虑到能否想办法把相同的元素都消除掉,这里我们就需要运用不常见的特殊运算符“^”— 按位异或运算。我们知道异或运算相同的位会消除,例4^4=(二进制)10^(二进制)10=(二进制)00,这样就消除了相同的数字。即使数组中相同数字是非连续的,根据加法的交换律,能够得到同样的结果。

(3)希望本文对你有所帮助。

算法代码实现如下:

	/**
	 * @author liqq
	 */
	public static int singleNumber(int[] A) {
		if (A.length == 0)
			return A[0];
		int x = A[0];
		for (int i = 1; i < A.length; i++) {
			x = x ^ A[i];
		}
		return x;
	}