3160. 所有球里面不同颜色的数目

Powered by:NEFU AB-IN

Link

3160. 所有球里面不同颜色的数目

题意

给你一个整数 limit 和一个大小为 n x 2 的二维数组 queries 。

总共有 limit + 1 个球,每个球的编号为 [0, limit] 中一个 互不相同 的数字。一开始,所有球都没有颜色。queries 中每次操作的格式为 [x, y] ,你需要将球 x 染上颜色 y 。每次操作之后,你需要求出所有球中 不同 颜色的数目。

请你返回一个长度为 n 的数组 result ,其中 result[i] 是第 i 次操作以后不同颜色的数目。

注意 ,没有染色的球不算作一种颜色。

思路

哈希表模拟即可

del 操作在 Python 的哈希表上是 𝑂(1),可以直接删除这一项
哈希表(如 Counter)的 len 操作的复杂度是 𝑂(1)

代码

'''
Author: NEFU AB-IN
Date: 2024-07-09 17:17:49
FilePath: \LeetCode\3160\3160.py
LastEditTime: 2024-07-09 17:31:23
'''
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, fabs, floor, gcd, log, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Dict, List, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)  # If using AR, modify accordingly
M = int(20)  # If using AR, modify accordingly
INF = int(2e9)
OFFSET = int(100)

# Set recursion limit
setrecursionlimit(INF)

class Arr:
    array = staticmethod(lambda x=0, size=N: [x] * size)
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])
    @staticmethod
    def to_1_indexed(data: Union[List, str, List[List]]):
        """Adds a zero prefix to the data and returns the modified data and its length."""
        if isinstance(data, list):
            if all(isinstance(item, list) for item in data):  # Check if it's a 2D array
                new_data = [[0] * (len(data[0]) + 1)] + [[0] + row for row in data]
                return new_data, len(new_data) - 1, len(new_data[0]) - 1
            else:
                new_data = [0] + data
                return new_data, len(new_data) - 1
        elif isinstance(data, str):
            new_data = '0' + data
            return new_data, len(new_data) - 1
        else:
            raise TypeError("Input must be a list, a 2D list, or a string")

class Str:
    letter_to_num = staticmethod(lambda x: ord(x.upper()) - 65)  # A -> 0
    num_to_letter = staticmethod(lambda x: ascii_uppercase[x])  # 0 -> A
    removeprefix = staticmethod(lambda s, prefix: s[len(prefix):] if s.startswith(prefix) else s)
    removesuffix = staticmethod(lambda s, suffix: s[:-len(suffix)] if s.endswith(suffix) else s)

class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)

class IO:
    input = staticmethod(lambda: stdin.readline().rstrip("\r\n"))
    read = staticmethod(lambda: map(int, IO.input().split()))
    read_list = staticmethod(lambda: list(IO.read()))

class Std:
    pass

# ————————————————————— Division line ——————————————————————

class Solution:
    def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:
        cnt_ = Counter()
        colors = Counter()
        res_list = []
        
        for x, y in queries:
            color = cnt_[x]
            if color:
                colors[color] -= 1
                if colors[color] == 0:
                    del colors[color]
            cnt_[x] = y
            colors[y] += 1
            res_list.append(len(colors))
        return res_list

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 19:30:07       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 19:30:07       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 19:30:07       58 阅读
  4. Python语言-面向对象

    2024-07-09 19:30:07       69 阅读

热门阅读

  1. go语言hassuffix的简单使用

    2024-07-09 19:30:07       31 阅读
  2. Vim常用整理快捷键

    2024-07-09 19:30:07       24 阅读
  3. Elasticsearch 分析器(Analyzer)的作用和配置

    2024-07-09 19:30:07       20 阅读
  4. html5 video去除边框

    2024-07-09 19:30:07       17 阅读
  5. 机器学习模型运用在机器人上

    2024-07-09 19:30:07       23 阅读
  6. 在网站存在漏洞的情况下强化安全防御

    2024-07-09 19:30:07       23 阅读
  7. 驱动开发系列-如何与硬件通信

    2024-07-09 19:30:07       27 阅读
  8. 计算机网络笔记分享(第六章 应用层)

    2024-07-09 19:30:07       33 阅读
  9. QT配置opencv

    2024-07-09 19:30:07       29 阅读