* 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?
package com.my.test.leco.bitoperation;
/**
* 题目:
* 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?
*/
public class SingleNumberII
{
private static final int INT_BIT_LEN = 32;
/**
* 思路:
* 1、统计每个二进制位(int长度32)的数字出现的次数和,该和取余3后剩余的,即为只出现一次的int值的二进制位的值
*
*/
public int singleNumber(int[] A) {
if (A == null || A.length <= 0) {
return 0;
}
int result = 0;
// 循环处理每个二进制位
for (int i = 0; i < INT_BIT_LEN; i++) {
int curBitCount = 0;
// 遍历数据,处理当前第i个二进制位上的数据
for (int a : A) {
int bit = (a >> i) & 1;
curBitCount += bit;
}
// 取余后得到当前二进制位是1还是0
curBitCount %= 3;
// 方案1、result右移i位与curBitCount取或后,再左移i位,后与result取或
// result |= ((result >> i) | curBitCount) << i;
// 方案2、curBitCount左移i位,后与result取或
result |= curBitCount << i;
}
return result;
}
/**
* 大牛解法1
*/
public int singleNumberII1(int[] A) {
if (A == null || A.length <= 0) {
return 0;
}
int ones = 0; // 记录只出现过1次的bits
int twos = 0; // 记录只出现过2次的bits
int threes;
for (int a : A) {
twos |= ones & a; // 要在更新ones前面更新twos
ones ^= a;
threes = ones & twos; // ones和twos中都为1即出现了3次
ones &= ~threes; // 抹去出现了3次的bits
twos &= ~threes;
}
return ones;
}
/**
* 大牛解法2
*/
public int singleNumberII2(int[] A) {
if (A == null || A.length <= 0) {
return 0;
}
int low = 0;
int high = 0;
for (int a : A) {
low = (low ^ a) & ~high;
high = (high ^ a) & ~low;
}
return low;
}
public static void main(String[] args)
{
int[] A = {1,2,1,3,2,1,2};
System.out.println(new SingleNumberII().singleNumber(A));
System.out.println(new SingleNumberII().singleNumberII1(A));
System.out.println(new SingleNumberII().singleNumberII2(A));
}
}
leetcode题目 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 co...