最小栈
Dequestack1; Deque stack2; public void pop() { //这里如果用==比较是比较两个Integer对象的地址,Integer能缓存(-128,127)这个范围的值,用==比较这个范围的值会返回true,超过这个范围用==比较就是不同的对象返回false,所以要equals进行比较,equals直接比较数值不比较地址 if (stack1.peek() == stack2.peek()) { stack1.pop(); stack2.pop(); } else { stack1.pop(); } } public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; }
比特位计数
暴力法
public int[] countBits(int n) {
int[] res = new int[n+1];
for (int i = 0; i <= n; i++) {
int mask = 1;
int count = 0;
for (int j = 0; j < 32; j++) {
if ((mask & i) != 0) {
count++;
}
mask <<= 1;
}
res[i] = count;
}
return res;
}
动态规划法
public int[] countBits(int n) {
int[] res = new int[n+1];
res[0] = 0;
for (int i = 1; i <= n; i++) {
//奇数的话1的位数就比前一个数多1
if (i % 2 == 1) {
res[i] = res[i-1] + 1;
} else {
//偶数的话1的位数就和除于2之后的位数一样
res[i] = res[i/2];
}
}
return res;
}
汉明距离
用异或,先x和y异或,不相等为1,然后再和1进行与
//左移找1
public int hammingDistance(int x, int y) {
int mask = 1;
int res = 0;
for (int i = 0 ; i < 32 ; i++) {
if ((mask & (x ^ y)) == mask) {
res++;
}
mask <<= 1;
}
return res;
}
//右移找1
public int hammingDistance(int x, int y) {
int res = 0;
int s = x ^ y;
while (s != 0) {
if ((s & 1) == 1) {
res++;
}
s >>= 1;
}
return res;
}



