It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.
Apparently, many engineers take measures on the site called LetCode.
It is a site that trains the algorithmic power that can withstand the coding test that is being done in the early story, and it is an inevitable path for those who want to build a career at an overseas tech company.
I wrote it in a big way, but I have no plans to have such an interview at the moment.
However, as an IT engineer, it would be better to have the same level of algorithm power as a person, so I would like to solve the problem irregularly and write down the method I thought at that time.
I'm solving it with Python3.
Leet Code Table of Contents Starting from Zero
Last time Leet Code Day 80 starting from zero "703. Kth Largest Element in a Stream"
Twitter I'm doing it.
** Technical Blog Started! !! ** ** I think the technology will write about LetCode, Django, Nuxt, and so on. ** This is faster to update **, so please bookmark it!
347. Top K Frequent Elements The difficulty level is Medium. Like the previous problem, it is a problem using Heap.
The problem is that you are given a non-empty array of numbers. Design an algorithm that returns the most frequent elements from the array up to the K
.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
I used Counter
to look up the elements of the list, got the key, and wrote it using heap's nlargest.
import heapq
import collections
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = collections.Counter(nums)
key = count.get
return heapq.nlargest(k,count.keys(),key)
# Runtime: 108 ms, faster than 66.40% of Python3 online submissions for Top K Frequent Elements.
# Memory Usage: 18.2 MB, less than 79.07% of Python3 online submissions for Top K Frequent Elements.
The arguments of nlargest
are in the order of n, iterable, key = None
.
So that's it for this time. Thank you for your hard work.
Recommended Posts