LeetCode算法题

诗人都在海底诗人都在海底 03月10日 22:45 发布于[机器学习]

167. Two Sum II - Input array is sorted

Given an array of integers that is already  most frequent elements.

Example 1:

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

Output: [1,2]

Example 2:

Input: nums = [1], k = 1

Output: [1]

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dict_top={}
        result=[]
        for i in nums:
            if i in dict_top:
                dict_top[i]+=1
            else:
                dict_top[i]=1
        sort_dict = sorted(dict_top.items(),key=lambda x:x[1],reverse=True)
        for j in sort_dict[:k]:
            result.append(j[0])
        return result  

75. Sort Colors

Given an array with n objects colored red, white or blue, sort them 

喜欢 | 0

登陆后发表文章

  • 0条回应给“LeetCode算法题”的评论