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
相关推荐
数模竞赛Paid answer9 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆9 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
想吃火锅100511 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil20811 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣12 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
qeen8715 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
lucas_AI15 小时前
1.2B 小模型赢过 235B 大模型:NaviDC-OCR 把文档解析卷明白了
人工智能·深度学习·算法
冻柠檬飞冰走茶16 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
民乐团扒谱机16 小时前
【微实验】倒谱算法(Cepstrum)深度解析:原理、数学推导与代码实现
人工智能·算法·语音识别
Nil20817 小时前
leetcode 189轮转数组
数据结构·算法·leetcode