为什么不使用一些简单的位操作呢?
public int commonDigits(int x, int y) {
int dX = 0;
while (x != 0) {
dX |= 1 << (x % 10);
x /= 10;
}
int count = 0;
while (y != 0) {
int mask = 1 << (y % 10);
if ((dX & mask) != 0) {
count ++;
dX &= ~mask;
}
y /= 10;
}
return count;
}
这段代码为x中的每个数字在dX中设置了一个相应的位。第二个循环中,对于x中的每个数字,代码会检查它是否在dX中有条目。如果是,则计数并重置位以避免重复计数(请注意,在您的代码中缺少此功能,请考虑123和141)。显然不使用任何额外的存储空间(如果需要,dX和count可以只是字节)。
请注意,您的解决方案中不需要使用HashTable--您可以使用HasSet或BitSet。
您的代码已转换为使用BitSet,并修复了重复计数问题:
public int commonDigits(int x, int y) {
int count = 0;
BitSet ht = new BitSet();
while (x != 0) {
ht.set(x % 10, true);
x /= 10;
}
while (y != 0) {
if ((ht.get(y % 10)) {
count++;
ht.set(y % 10, false);
}
y /= 10;
}
return count;
}
两个代码片段的作用完全相同,后者只是在比特集合(BitSet)(和嵌入的数组)实例中有一些额外开销。
本文展示了为什么在一般情况下BitSet比布尔数组更好:
http://chrononsystems.com/blog/hidden-evils-of-javas-byte-array-byte
编辑:
如果要多次计数相同的数字(从问题的示例中不清楚是否需要),请使用int数组来存储计数:
public int commonDigits(int x, int y) {
int count = 0;
int[] digits = new int[10];
while (x != 0) {
digits[x % 10]++;
x /= 10;
}
while (y != 0) {
if (digits[x % 10] > 0) {
count++;
digits[x % 10]--;
}
y /= 10;
}
return count;
}
int[10]
也足够了... - Fildor