• LeetCode只出现一次的数字


    剑指 Offer II 004. 只出现一次的数字

    给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。

    输入:nums = [2,2,3,2]
    输出:3

    来源:LeetCode

    用Map集合解题。
    关于Map集合中的方法:
    1.put(key,value),将key-value加入到map集合中
    2.getOrDefault(num,0):如果在map中存在num,就不返回默认值0,也就是遍历nums的过程中对nums中的元素进行计数。
    3.Map.Entry是map中的一个接口,表示一个映射项,有getKey和getValue方法。

    思路:
    先遍历nums数组,对元素进行计数,并将结果记录到map集合中。
    遍历map集合,如果有value==1的,返回相应的key。

    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);
            }
            int ans=0;
            for(Map.Entry<Integer,Integer> entry : map.entrySet()){
                int a=entry.getKey(),b=entry.getValue();
                if(b==1){
                    ans=a;
                    break;
                }
            }
            return ans;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    关键是对于map集合有关方法的使用。

    官方题解里面给出了位运算的方法,将所有元素转换成二进制,然后对每一位进行相加,对3取余(如果不是最终答案的元素,每个数字出现三次),结果得到的数就是最终答案的二进制位。

    例如【2,2,3,2】
    转换成二进制位分别是:10,10,10,11
    所以首位是(1+1+1+1)%3=1,第二位是(0+0+0+1)%3=1
    最终答案就是11,也就是3

    对于题解中给出的有关数字电路的解法还没太看懂。

    官方题解

  • 相关阅读:
    Auracast 广播音频知识点
    Windows右键添加用 VSCODE 打开
    完美解决Android adb install 安装提示 INSTALL_FAILED_TEST_ONLY
    vue3使用腾讯地图选择地点
    刷题记录:牛客NC16590乌龟棋
    Mybatis---从入门到深化
    Javassist-ConstPool常量池
    提高 JavaScript 可读性的 10 个技巧
    100 寻找重复数
    手写一个自己的mystrstr
  • 原文地址:https://blog.csdn.net/liyatjj/article/details/126986098