暱稱: 呆呆獸 Slowpoke
👨💼: Interviewer
🙋♂️: Intreviewee
👨💼: 今天的面試,我們希望你能夠實作 Remove Element,這個算法可以幫助我們快速地清理數據,我們會給你一段整數 array 跟一個指定的整數 K,希望你能將所有等於 K 的值排列在 array 的最前面,並回傳不等於 K 的數量,array 內的其他數值以及 array 的大小並不重要。要注意的是,所有動作必須要 in-place。
👨💼: Array 的長度為 0~100,數值大小介於 0~50。
🙋♂️: 我想舉個例子確認一下題意。
🙋♂️: 請問這個例子正確嗎?
👨💼: 沒有問題。
🙋♂️: 我的想法是使用一個 for 迴圈去看過每一個數值,如果不等於 K,就會把他往前放,所以我會再添加一個指標來記錄上次往前放的位置。
👨💼: 了解,你可以開始進行實作了。
🙋♂️: 由於只有一層 for 迴圈,所以時間複雜度為 。
👨💼: 程式碼沒問題。
👨💼: 但你的程式看似有一些多餘的步驟,比如在你的舉例當中,1 會寫入 1 自己的位置,你有什麼解決辦法嗎?
🙋♂️: 那我另一個指標應該要從 array 的後面開始找,如果前面的指標遇到等於 K 的數字,就要跟後面指標交換,接著更新指標位置,直到前後指標重合。
👨💼: 看起來沒什麼問題,我們再舉個例子測試一下。
👨💼: Okey,沒有問題。
👨💼: 但在現實情境中,有時候我們會希望資料經過刪除後,同時資料所占用的空間也變少。對應到這個題目,我們希望在 Remove Element 後, capacity 也可以降低,你會怎麼修改呢?
🙋♂️: 我會使用 C++ 中 copy 跟 swap 的特性來完成,首先將原本的 array 複製一份到新的空間,這個步驟配置剛剛好的容量,接下來使用 swap 來改變記憶體位置。
👨💼: "3Sum" 是一個經典的算法問題,稍加改良後,能夠應用在資料庫查詢或金融交易分析中。在這個問題中,輸入會是一串整數,我們希望找出所有不重複的三個數字組合,使它們的總和等於零,請注意你的答案不能有重複的組合。
👨💼: 總共有 3 ~ 3000 個數值,數值的大小介於 ~
🙋♂️: 請問 input 和 output 的資料型態, 我可以假設是 C++ 中的 vector 嗎?
👨💼: 可以這樣假設。
🙋♂️: 好的,為了更好的理解題目,我想舉個例子確認一下。
🙋♂️: 請問這樣有符合題意嗎?
👨💼: 這樣有符合。
🙋♂️: 那如果找不到符合條件的解,是不是回傳空的 vector 即可?
👨💼: 對。
🙋♂️: 我最初步的想法,是使用三層迴圈去找到所有解,並使用集合去儲存這些解以避免重複,不過這個演算法的時間複雜度是 ,非常沒有效率,所以我會想使用雙指標來解決這個問題。首先,先對所有數值做升冪排序,接著使用一層 for 迴圈,每次固定一個值,剩下兩個值使用雙指標去選出來。
👨💼: 了解,你可以開始進行實作了。
🙋♂️: 排序的時間複雜度為 ,迴圈跟雙指標的時間複雜度為 ,所以這個演算法的時間複雜度為 。
👨💼: 你目前的演算法有用到集合,插入元素的時候,會需要維護的成本,如果不要使用集合,你有什麼想法嗎?
🙋♂️: 有的,重複的組合是由於相同的數值被選擇多次造成的,我們可以利用排序過後的特性,當連續出現相同數值時,可以直接跳過,來避免選到重複的組合。
👨💼: Now I want to discuss a question about binary trees, "Average of Levels in Binary Tree" The number of nodes in the tree is in the range [1, 100]. Please follow the definition below for the structure of the binary tree.
🙋♂️: Could the node values be float?
👨💼: Let's assume they are integers.
🙋♂️: Okey. I want to provide an example to help me understand the question.
🙋♂️: In this example, I need to return [3, 14.5, 11]. Did I get it right? Even though the input values are integers, the output values might be float.
👨💼: Yes, your understanding is right.
🙋♂️: For this question, my initial idea is to use DFS to visit each node and use a table to keep track of the total sum and the number of nodes at each level. Finally, we can calculate the average.
🙋♂️: Since DFS visits each node only once, the time complexity is , and the space complexity is also because, for imbalanced trees, the depth of recursion could be equal to the number of nodes.
👨💼: It looks good, but in some cases, I might only want to calculate the average for a specific level. With your method, I would still have to traverse the entire tree. Do you have a way to improve this issue?
🙋♂️: I want to use BFS to visit each node layer-by-layer and calculate the average for nodes on the same level. This way, we can compute averages in the order we want.
🙋♂️: The time complexity and space complexity are both . This is because BFS visits each node only once, and in the worst case, all nodes might be stored in the queue.