• Leetcode中等:137. 只出现一次的数字II


    题目:只出现一次的数字II

    • 题号:137
    • 难度:中等
    • https://leetcode-cn.com/problems/single-number-ii/

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

    你必须设计并实现线性时间复杂度的算法且不使用额外空间来解决此问题。

    示例 1:

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

    示例 2:

    输入:nums = [0,1,0,1,0,1,99]
    输出:99
    
    • 1
    • 2

    提示

    • 1 < = n u m s . l e n g t h < = 3 ∗ 1 0 4 1 <= nums.length <= 3 * 10^4 1<=nums.length<=3104
    • − 2 31 < = n u m s [ i ] < = 2 31 − 1 -2^{31} <= nums[i] <= 2^{31} - 1 231<=nums[i]<=2311
    • nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次

    实现

    第一种:累加法

    原理:[a,a,a,b,b,b,c,c,c][a,a,a,b,b,b,c]差了2c

    3*(a+b+c)-(a+a+a+b+b+b+c)=2c

    所以,唯一的数是c/2。想法很简单,但提交的时候溢出了。

    C# 语言

    public class Solution
    {
        public int SingleNumber(int[] nums)
        {
            int s = nums.GroupBy(a => a).ToList().Sum(a => a.Key) * 3;
            int result = s - nums.Sum(a => a); // System.OverflowException
            return result / 2;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    第二种:利用字典的方式

    把字典当作一个存储容器,key 存储数组中的数字,value 存储该数字出现的频数。

    C# 语言

    public class Solution
    {
        public int SingleNumber(int[] nums)
        {
            Dictionary<int, int> dict = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                if (dict.ContainsKey(nums[i]))
                {
                    dict[nums[i]]++;
                }
                else
                {
                    dict.Add(nums[i], 1);
                }
            }
            return dict.Single(a => a.Value == 1).Key;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    Python 语言

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            dic = dict()
            for num in nums:
                if num in dic:
                    dic[num] += 1
                else:
                    dic[num] = 1
    
            for k, v in dic.items():
                if v == 1:
                    return k
            return -1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    第三种:利用位运算

    思路:

    初始result = 0,将每个数想象成 32 位的二进制,对于每一位的二进制的1累加起来必然是3N或者3N + 1(出现3次和1次);3N代表目标值在这一位没贡献,3N + 1代表目标值在这一位有贡献(=1),然后将所有有贡献的位记录到result中。这样做的好处是如果题目改成k个一样,只需要把代码改成count % k即可,很通用并列去找每一位。

    C# 语言

    public class Solution
    {
        public int SingleNumber(int[] nums)
        {
            int result = 0;
            for (int i = 0; i < 32; i++)
            {
                int mask = 1 << i;
                int count = 0;
                for (int j = 0; j < nums.Length; j++)
                {
                    if ((nums[j] & mask) != 0)
                    { //该位为1才 !=0
                        count++;  //该位1出现的次数
                    }
                }
                if (count % 3 != 0)
                {
                    result |= mask;
                }
            }
            return result;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    Python 语言

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            result = 0
            for i in range(32):
                mask = 1 << i
                count = 0
                for num in nums:
                    if num & mask != 0:
                        count += 1
                if count % 3 != 0:
                    result |= mask
                if result > 2 ** 31-1:
                    result -= 2 ** 32
            return result
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    注意:Python的整型方便是方便了,但是由于其没有最大值,所以,当输出是负数的时候,会导致认为是正数!因为它把32位有符号整型认为成了无符号整型,所以这就是Python的一个坑。

  • 相关阅读:
    Python----33个保留字列表、内置函数列表、datetime库 、random库、jieba库、math库
    【Java】this、super关键字,代码块介绍
    PostgreSQL VACUUM 之深入浅出 (二)
    OAuth2 的基本概念
    Java -- SpringSession实现session共享
    UE XML解析
    JavaScript函数进阶学习
    流数据湖平台Apache Paimon(三)Flink进阶使用
    Vue中props的默认值defalut使用this时的问题
    由于执行触发器导致登录失败,错误号为17892的解决方案
  • 原文地址:https://blog.csdn.net/AlgorithmCharm/article/details/127133165