[LeetCode] 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?

分析:

因为我先做的Single Number II,所以自然想到那道题的思路:由于不让用extra memory,我们保存一个32位的array,来记录array中每一个数的为1的位。由于除了一个数以外的所有数都是出现了两次,他们的对应为1的位累计之和肯定可以被2整除;而只出现一次的那个数对应的1的位,肯定不能被2整除。

代码:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int count[32] = {0};
		int result = 0;
		for (int i = 0; i < 32; i ++) {
			for (int j = 0; j < n; j ++) {
				int num = A[j];
				count[i] += (num >> i) & 1;
			}

			result |= ((count[i] % 2) << i);
		}
		return result;
    }
};

经过在网上搜索,我发现了另外一个答案:使用exclusive or。XOR的特点是:如果两个operand一样(比如都是1或者都是0),那么就返回0;如果不一样,则返回1。值得注意的是,根据这个性质,0 XOR a = a for any a. 也就是说,一个数跟零进行exclusive or,结果就是那个数不变。还有就是,如果是两个相同的数进行XOR,则结果为0,因为它们的每一位都是一样的,所以每一位的结果都是0。最后,XOR满足交换律。所以我们需要做的就是:把array中所有的数一个一个XOR下去,那么由于交换律,我们可以把相同的两个数都放在一起,所以变成了0;最后只剩下0与只出现一次的那个数进行XOR,那结果就是只出现过一次的那个数。

代码:

class Solution {
public:
	int singleNumber(int A[], int n) {
		int result = 0;
		for (int i = 0; i < n; i ++) {
			result ^= A[i];
		}
		return result;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值