python 刷leetcode 题目(36)

347前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 高的元素。

例如,

给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]

注意:

  • 你可以假设给定的 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , 是数组的大小。

思路:运用python的内置函数

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        #### 最先想到就是python的内置函数来解决这个问题
        # from collections import Counter
        # c = Counter(nums)
        # res = []
        # for item in c.most_common(k):
        #     res.append(item[0])
        # return res
        
        #### the second method
        data, res = {}, []
        for num in nums:
            data[num] = data[num] + 1 if num in data else 1
        sorted_data= sorted(data.items(), key=lambda x: x[1], reverse=True)
        for i in range(k):
            res.append(sorted_data[i][0])
        return res
    
        

python几种根据的value值进行排序的方法:

sorted_data= sorted(data.items(), key=lambda x: x[1], reverse=True)  ### 利用内置函数 

import operator
sorted_data = sorted(data.items(), key = operator.itemgetter(1), reverse=True) #### 借助operator

f = zip(data.values(),data.keys())  ### zip 函数,zip 之后,zip函数默认会对第一个元素进行排序的,如何取消排序?测试没有成功
sorted_data = sorted(f, reverse=False)

数组中的第K个最大元素

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4

代码:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        #### the first method
        # nums = sorted(nums, reverse = True)
        # return nums[k-1]
        
        #### the second method,使用的是冒泡排序,很遗憾,超时了
        for i in range(len(nums)-1, -1, -1):
            for j in range(i):
                if nums[j] < nums[j + 1]:
                #     temp = nums[j]
                #     nums[j] = nums[j + 1]
                #     nums[j + 1] = temp
                    nums[j], nums[j+ 1] = nums[j+1], nums[j]
        return  nums[k-1]
    


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值