您的位置:首页 > 其它

[LeetCode]Single Number II

2014-04-24 21:25 337 查看

题目:

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.
Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

来源:http://oj.leetcode.com/problems/single-number-ii/

思路:

这里用了sort排序,其实有点不符合题目要求,因为sort时间为o(nlgn)。网上还有一种使用位运算的方法,不过真心有点难懂啊。。。难度系数真大啊

C++ AC代码:

class Solution {
public:
int singleNumber(int A[], int n) {
if(n<=0) return -1;
if(n==1) return A[0];

sort(A, A + n);
int j = 1;
for(int i = 0; i < n - 1; i++)
{
if(A[i] == A[i+1])
j++;
else
{
if(j<3) return A[i];
j = 1;
}
}
return A[n-1];
}
};

运行时间 84ms

使用位运算的解法:
class Solution {
public:
int singleNumber(int A[], int n) {
int one = 0, two = 0, three = 0;
for (int i = 0; i < n; ++i) {
two |= one & A[i]; //出现两次的 就加到B里面
one ^= A[i]; //从A里面删除 出现两次的
three = one & two;  //如果是三次的 就会同时出现在A和B里面,
one &= ~three; //然后删除A里三次的
two &= ~three;  //删除B里三次的
}
return one;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: