Top K Frequent Elements

Intuition

in order to solve this problem first we have to travel every element in this array and pick up the highest frequent occurrences number which is designate by k.

Approach

first we implement a dictionary to store the number and the frequency then we travel all the elements in array. If the number is included the frequency should plus 1.if the number is not included the frequency should be set to 1.then set a tuple to recive all the numbers and its frequency.in order to obtain the top k highest frequency numbers we arrange them in descending order.At last we can travel top k highest frequenct numbers to get the result.

Complexity

  • Time complexity:

the first setp travel numbers will take O(n) and the second step travel will take O(n) the third step due to the properties of the sort function in python which is implemented timesort algorithm it will take O(nlog(n)) and the forth step will take O(k).So the final time complexity is O(nlog(n)).

  • Space complexity:

To maintain the hash table it will take O(n) space complexity

Code

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

        element_fre=[(num,freq) for num,freq in frequency.items()]

        element_fre.sort(key=lambda x: x[1],reverse=True)

        result=[element for element,_ in element_fre[:k]]
        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值