【Leetcode长征系列】Single Number

来源:互联网 发布:农业大数据平台 编辑:程序博客网 时间:2024/04/29 23:03

原题:

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,2,4,8,4,1]

它们的二进制表示出来分别为[ 0001,0010,0010,0100,1000,0100,0001 ]

所以如果从二进制的角度去思考,这个问题就很简单了:

0001

0010

0010

0100

1000

0100

0001

我们如果对每一列都做异或运算的话,最后剩下的一定是只有基数个的那个数字,因为异或的特点是相同为0,不同为1

所以题目中要求的线性时间计算以及不开辟另外的空间是完全可以实现的。

代码如下:

int singleNumber(int A[], int n){

int res = 0;

for (int i=0; i<n; i++)

res = res^A[i]

return res;

}

知道真相的我真实叹为观止阿…小菜遁地飘走。

0 0
原创粉丝点击