Problem:Single Number I
Given an array of integers, every element appears twice except for one. Find that single one.
Note:Your algorithm should have alinear runtime complexity. Could you implement it without using extra memory?
代码如下:
class Solution {
public:
int singleNumber(int A[], int n) {
if(n>=0){
int result = 0;
for(;n>0;n--){
result = A[n-1] ^ result;
}
return result;
}
else
return -1;
}
};
这个问题主要考虑到亦或运算符的运算规则:
1^1=0; 0^0=0; 1^0=1;
a^b^c=a^(b^c)=(a^b)^c;
我submit时一开始并没有想到这种方法,而是采用了先快排,在查找的办法,测试也可以通过,但时间复杂度是n*logn,可能是在n直很小时,无法区分这两种复杂度的区别。代码如下:
#include <algorithm>
using namespace std;
class Solution {
public:
int singleNumber(int A[], int n) {
sort(&A[0], &A[n]);
for(;--n>=0;){
if(A[n]!=A[n-1]){
return A[n];
}
else if(n == 0){
return A[0];
}
else
n--;
}
}
};
这种方式利用stl库里的sort()算法,先快排,再查找。
另外leetcode oj上不能使用cout等,否则会报错,一开始的错误千奇百怪,后来才发现。本人新手,还是要多加练习啊!