剑指offer 只出现一次的数字Java

力扣题目链接
不知道别的方法怎么样,只能想出HashMap

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int num :nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        for(Map.Entry<Integer,Integer> entry: map.entrySet()){
            if(entry.getValue().equals(1)){
                return entry.getKey();
            }
        }
        return -1;
    }
}


力扣大佬的代码1ms

class Solution {
    //将整数的各个数位上的加起来,然后对3取余,若结果为0,则待求数字在该位上是0;
    //若结果为1,则待求数字在该位上是1.
    public int singleNumber(int[] nums) {
        //java的int整型为32位
        int[] arr=new int[32];
        for(int num:nums){
            for(int i=0;i<32;i++){
                arr[i]+=(num>>(31-i))&1;
            }
        }
        int res=0;
        for(int i=0;i<32;i++){
            res=(res<<1)+arr[i]%3;
        }
        return res;
    }
}
posted @   蹇爱黄  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示