LeetCode347. 前k个高频元素,栈

1. 题目描述

题目来源:力扣

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例1.
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例2.
输入: nums = [1], k = 1
输出: [1]

2. 题解

解题思路,利用字典,统计nums中每个数字出现的次数。

dic{数字:次数}

根据出现的次数,对其进行排序。这里选用栈,过程如下:

(1)若是数字未在栈中,将数字放入栈顶;

(2)若数字出现在栈中,和前面的元素的次数比较,若是大,则前移,直到小于为止。

返回栈底k个元素。

代码如下,

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        dic = {}
        queue = []
        for i in nums:
            if i not in dic.keys():
                dic.setdefault(i, 1)
            else:
                dic[i] += 1
            queue = self.insert(queue, dic, i)
        return queue[0:k]


    def insert(self, queue, dic, i):
        if i not in queue:
            queue.append(i)
            return queue
        else:
            index_i = queue.index(i)
            index_j = index_i - 1
            while index_j >= 0 and dic[queue[index_i]] > dic[queue[index_j]]:
                index_j -= 1
            queue.pop(index_i)
            queue.insert(index_j + 1, i)
            return queue

if __name__ == '__main__':
    sol = Solution()
    nums = [1,]
    k = 1
    r = sol.topKFrequent(nums, k)
    print(r)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值