题目:
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?
思路:
这一题原来听过,对位运算敏感度人可能会想到两个相等的数进行异或运算结果为零,而零与任何不为零的数异或运算结果都为这个不为零的数本身,基于此,把数组内所有元素串联进行异或,那些配对的经过异或都变成零了,而落单的最终一定是和零进行异或,结果必然是它自己。异或的顺序要不要紧呢?不要紧,异或运算是有结合律的,不在意顺序,所以不用在意这个细节。
代码:
class Solution { public: int singleNumber(int A[], int n) { int re; for(int i=0;i<n;i++) { re=re^A[i]; } return re; } };
时间: 2024-10-08 10:33:55