您的位置:首页 > 其它

[LeetCode]Single Number II

2014-03-05 15:49 176 查看

题目描述

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?

解题思路

因为java里int始终占4个字节,32位。所以我们可以对外层循环遍历32次,然后内层循环记录0-31位每一位出现的次数,内层循环结束后将结果取余于3即为当前位的值。
时间复杂度O(32 * n), 空间复杂度O(1)

代码

public int singleNumber(int[] A) {
int bit, result = 0;

for (int i = 0; i < 32; i++) {
bit = 0;
for (int j = 0; j < A.length; j++) {
if (((A[j] >> i) & 1) == 1) {
bit++;
}
}

bit = bit % 3;

result |= bit << i;
}

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