栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣hot100

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣hot100

最小栈

Deque stack1;
 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;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/274035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号