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
相关推荐
老马啸西风19 分钟前
力扣 LC27. 移除元素 remove-element
算法·面试·github
数智顾问23 分钟前
中秋特别篇:使用QtOpenGL和着色器绘制星空与满月——从基础框架到光影渲染
算法
txwtech26 分钟前
第5篇 如何计算两个坐标点距离--opencv图像中的两个点
人工智能·算法·机器学习
CoovallyAIHub26 分钟前
YOLO26学界首评:四大革新点究竟有多强?
深度学习·算法·计算机视觉
用户9163574409526 分钟前
LeetCode热题100——11.盛最多水的容器
javascript·算法
Gorgous—l40 分钟前
数据结构算法学习:LeetCode热题100-矩阵篇(矩阵置零、螺旋矩阵、旋转图像、搜索二维矩阵 II)
数据结构·学习·算法
2401_841495641 小时前
【计算机视觉】霍夫变换函数的参数调整
人工智能·python·算法·计算机视觉·霍夫变换·直线检测·调整策略
练习前端两年半1 小时前
🔍 你真的会二分查找吗?
前端·javascript·算法
搂鱼1145142 小时前
GJOI 10.7/10.8 题解
算法
Django强哥2 小时前
JSON Schema Draft-07 详细解析
javascript·算法·代码规范