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
相关推荐
liulilittle2 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
郝学胜-神的一滴6 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
青少儿编程课堂1 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu1 天前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗1 天前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
凌冰_1 天前
数据结构 - 队列(五)
数据结构·算法·软件工程
让我们一起加油好吗1 天前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
让我们一起加油好吗1 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
lisw052 天前
稀疏算法概述!
算法·机器人·无人机