您的位置:首页 > 其它

Single Number(leetcode)

2014-11-15 10:40 381 查看
题目:

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?
题目来源:https://oj.leetcode.com/problems/single-number/
解题思路:两个相同数字的异或为0,不断进行异或,最后得到的数即使所求。

#include<iostream>
using namespace std;

int singleNumber(int A[], int n)
{
if(n<0)
return 0;
int result=A[0];
for(int i=1;i<n;i++)
result^=A[i];
return result;
}

int main()
{
const int N=5;
int A[]={2,2,1,1,3};
int result=singleNumber(A,N);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: