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

你可能感兴趣的:(算法)