347. Top K frequent Elements [medium] (Python)

Source: Internet
Author: User

Topic links

https://leetcode.com/problems/top-k-frequent-elements/

Original title

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2] .

Note:

  1. You may assume k are always valid, 1≤k≤number of unique elements.
  2. Your algorithm's time complexity must be better than O (n log n), where n is the array ' s size.
Method of Thinking

The key to solving this problem is to control the complexity of the time "less than O (NLOGN)" This condition.

Idea one

According to my thinking habits, see this problem, the first thought is the following ideas: First use dict to get all the number of different numbers, and then the number of orders, take the number of the first k of the corresponding number can be. The code below, however, uses the built-in sorted () function, which can only say that the time complexity is less than or equal to O (Nlogn), not quite satisfied with the test instructions appearance, for reference only. "Time Complexity O (NLOGN)"

Code

 class solution(object):     def topkfrequent(self, nums, k):        "" : Type Nums:list[int]: type K:int:rtype:list[int] "" "Data, res = {}, [] forIinchNums:data[i] = Data[i] +1 ifIinchDataElse 1Sorted_data = sorted (Data.iteritems (), Key=operator.itemgetter (1), reverse=True) forIinchXrange (k): Res.append (sorted_data[i][0])returnRes
Idea two

Based on the above ideas, improve the time complexity by improving the sequencing steps. Consider the use of time complexity with only O (n) buckets sorted (bucket sort), while consuming space complexity O (n). The code is as follows. "Time complexity O (n)"

Code

 class solution(object):     def topkfrequent(self, nums, k):        "" : Type Nums:list[int]: type K:int:rtype:list[int] "" "Data, res = {}, [] forIinchNums:data[i] = Data[i] +1 ifIinchDataElse 1bucket = [[] forIinchXrange (Len (nums) +1)] forKeyinchData:bucket[data[key]].append (Key) forIinchXrange, Len (bucket)-1, -1, -1):ifBucket[i]: Res.extend (Bucket[i])ifLen (res) >= K: Break        returnRES[:K]
Three Ideas

or along the line of thought one, in addition to the bucket sort, the priority queue can satisfy the requirements of the solution. Many languages have built-in priority queue structures, queue.priorityqueue in Python, and more efficient HEAPQ (using the list to simulate the heap), where HEAPQ is used. "Time Complexity O (NLOGK)"
Note: Since HEAPQ is the smallest heap by default, the code adds a minus sign to the weight on the heap's push, so that the top of the heap is actually the most frequently occurring number.

Code

 class solution(object):     def topkfrequent(self, nums, k):        "" : Type Nums:list[int]: type K:int:rtype:list[int] "" "Data, res, PQ = {}, [], [] forIinchNums:data[i] = Data[i] +1 ifIinchDataElse 1         forKeyinchData:heapq.heappush (PQ, (-data[key], key)) forIinchXrange (k): Res.append (Heapq.heappop (PQ) [1])returnRes
Idea four

In fact, a lot of Python's built-in functions are handy when it comes to solving this kind of counting problem, but I'm not sure about the internal implementation, but here's a bit of growth posture:)

Code One

class Solution(object):    def topKFrequent(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: List[int]        """        counter = collections.Counter(nums)        return [item[0forin counter.most_common(k)]

Code two

class Solution(object):    def topKFrequent(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: List[int]        """        counter = collections.Counter(nums)        return heapq.nlargest(k, counter, key=lambda x: counter[x])

PS: Write wrong or write not clear please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/52075042

347. Top K frequent Elements [medium] (Python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.