leetcode2670找出不同元素数目差数组

题目链接

2670. 找出不同元素数目差数组 - 力扣(LeetCode)

解题思路

暴力破解
复制代码
class Solution:
    def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
        mapbefore = [1] * len(nums)
        tmp = [nums[0]]
        for i in range(1,len(nums)):
            if nums[i] not in tmp:
                tmp.append(nums[i])
                mapbefore[i] = mapbefore[i - 1] + 1
            else:
                mapbefore[i] = mapbefore[i - 1]
        print(mapbefore)

        mapafter = [0] * len(nums)
        tmp = []
        for i in range(len(nums) - 2, -1, -1):
            if nums[i + 1] not in tmp:
                tmp.append(nums[i + 1])
                mapafter[i] = mapafter[i + 1] + 1
            else:
                mapafter[i] = mapafter[i + 1]
        print(mapafter)
        result = []
        for i in range(0,len(nums)):
            result.append(mapbefore[i]-mapafter[i])
        return result
使用set()
复制代码
class Solution:
    def distinctDifferenceArray(self, nums: List[int]) -> List[int]:
        st = set()
        sufCnt = [0] * (len(nums) + 1)
        for i in range(len(nums) - 1, 0, -1):
            st.add(nums[i])
            sufCnt[i] = len(st)
        res = []
        st.clear()
        for i in range(len(nums)):
            st.add(nums[i])
            res.append(len(st) - sufCnt[i + 1])
        return res
相关推荐
AI科技星4 分钟前
乖乖数学·全域超复数统一场论:五大核心门槛与全套标准定量数据
人工智能·python·算法·金融·全域数学
Frostnova丶43 分钟前
(13)LeetCode 53. 最大子数组和
算法·leetcode·职场和发展
什巳1 小时前
JAVA练习277- 找到字符串中所有字母异位
java·开发语言·算法·leetcode
机器学习之心1 小时前
基于遗传粒子群混合算法的无人机三维路径规划:Matlab 实现与多算法对比分析
算法·matlab·无人机·无人机三维路径规划·遗传粒子群混合算法
本王是暴君1 小时前
AutoMem:把 Agent Memory 变成可训练的记忆管理技能
人工智能·算法·数据挖掘
zmzb01031 小时前
C++课后习题训练记录Day154
数据结构·c++·算法
木木子226 小时前
# 密码强度检测深度解析:正则表达式实时分析、多维度评分算法与可视化反馈
mysql·算法·华为·正则表达式·harmonyos
Sw1zzle9 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
万法若空10 小时前
【算法-查找】查找算法
java·数据结构·算法
海石10 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode