[Python] Stuck at a test case cant understand the prolem

Discussão em 'Python' iniciado por Stack, Julho 4, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to improve my coding skills and I got stuck at a question and can't understand the test case. I passed the first 5 test cases but got stuck at the last one:

    Top K Frequent Elements


    Given an integer array nums and an integer k, return the k most frequent elements within the array.

    The test cases are generated such that the answer is always unique.

    You may return the output in any order.

    Example 1

    • Input: nums = [1,2,2,3,3,3], k = 2
    • [2,3]
    Example 2

    • Input: nums = [7,7], k = 1
    • Output: [7]
    ​

    I got stuck on this test case:

    Input: nums=[1,2] k=2

    Output: [1,2]

    My code:


    class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
    number_map={}
    result=[]
    for num in nums:
    if num in number_map:
    number_map[num] +=1
    else:
    number_map[num] = 1
    for num in number_map:
    if number_map[num] >= k:
    result.append(num)

    return result


    I want to know why it doesn’t work for

    nums=[1,2] k=2

    Continue reading...

Compartilhe esta Página