0%

LeetCode 347 - Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

example

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

How can we solve this problem?

這一題需要我們返回K個數量最多的element。所以,我們可以使用map記錄我們array中element的個數,然後在把他們以<frequency,element>存到priority queue/max queue,最後只要返回priority queue中的k個element即可。

LeetCode 703 - Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.

example:

Reward

這是我跟組員們一起討論、辛苦了多個日夜,能一起做寫程式,分享知識的感覺真的很棒><。雖然不知道以後還沒有機會一起合作,但還是非常感謝他們願意陪我躲在實驗室裡面一整天(╥╯^╰╥)。希望他們能好好生活,好好學習!

什麼是Abstract Factory(抽象工廠)呢?

定義: 又稱為Kit模式。提供一個創建系列相關或者互相依賴的Interface,而無需指定其具體的class

簡單例子

注: 以下程式單純用於解釋,並不能實際執行

基於Gin實作Rate Limiter

假設我們有2個APIs,而每個API都需要消耗1個Tokens

urimethoddesc
/api/posts/{id}GETreturn a simple demo message
/pingGETreturn pong

我們先設置一下rate limiter桶子的容量只能放下一個tokens,而tokens則會每秒生產5個。存取API時,若沒有Token可以用,就需要等待token下一次生產並放到桶子裡,才能繼續進行下去。

Token Bucket(令牌桶算法)

什麼是Token Bucket 呢?

簡單來說就是運用Token Bucket的系統會以一個設定的速率往桶子(Bucket)裡面丟令牌(Token)。如果請求(Request)需要被處理時,就必需得Bucket裡的Token。當桶子裡面的沒有Token可以分配/獲取時,也就是說Bucket現在是空的(Token已經被其他令牌拿完了),系統則會拒絕這個請求的服務。

什麼是Factory(工廠)呢?

定義:建立一個接口,讓子類自己決定實現哪一個Factory,其重點是繼承了Simple Factory Patterns的優點,同時解決了它的問題

什麼是Simple Factory(簡單工廠)呢?

簡單而言就是: 由一個工廠來生產全部產品 定義:建立一個接口,讓子類自己決定實現哪一個Factory,重點在於工廠,透過工廠的Static method 進行生成的Object

什麼是Design Pattern(設計模式)呢?

設計模式(Design Pattern) 是對軟體設計中普遍存在(反覆出現)的各種問題,所提出的解決方案。用於描述在各種不同的情況下,如何解決問題的一種方案