1. 程式人生 > >Airbnb的面經複習筆記

Airbnb的面經複習筆記

12/1

1. Collatz Conjecture

/*
If a number is odd, the next transform is 3*n+1
If a number is even, the next transform is n/2
The number is finally transformed into 1.
The step is how many transforms needed for a number turned into 1.
Given an integer n, output the max steps of transform number in [1, n] into 1.
*/

1. 對於1到n的每一個數,都計算一遍(一個for迴圈)。

2. 對於每一個數,用以上公式計算step數。

3. 在每一個for迴圈結束前,用max來拿到/記錄當前最大的步數,以及這個步數所對應的數。

4. 最後,return那個最大步數所對應的數字。

-> 邊界條件,如果給的數小於1,return 0. 如果給的數等於1,return 1.

-> 這道題有兩種寫法,一種是iteration,一種是recursion。我自己寫是用iteration寫的,然後給的參考程式碼是用recursion寫的,儘量保證兩種都會。

-> 在參考程式碼裡有一種優化寫法。參考程式碼定義了一個hashmap作為全域性變數,然後,對於每一個[1, n]中的數,都把它和它最後的step數記錄到這個hashmap裡。然後在recursion的計算過程中,在計算每個數之前,先check這個數是否在hashmap裡有過歷史記錄,如果有這個歷史記錄,就可以直接用hashmap裡的結果,而不是去再算一遍。這樣以增加空間complexity為代價,略微提高了時間complexity。

 

2. Implement Queue with Limited Size of Arrays

/* implement 一個 queue,但是要求用 int[]儲存,並且一次生成的 int[]長度不可以超過 5。其實這是 一個記憶體分配的模型,每個 int[]可以看成一個 block 的抽象,每次需要加更多元素的時候就要申 請多分配 block,remove 的時候就要回收 block。*/

問題:1. If I have a return type for poll(), what is the return value when there's no elements inside the array?

-> 在push裡,如果tail的index到了fixedSize - 1 (或者fixedSize?),建一個新的list,把當前的數字加到新list裡去,然後把新list加進老list裡,然後讓tailList指向新的list。

tailList = (List<Object>)tailList.get(tail); 然後把tail這個index設定成0. 如果沒有到,就直接往tailList裡面加元素。完了之後increase count,increase tail這個index。

-> 在poll裡,如果count是0,return null。然後用head index得到head的value,increase head index,並且decrease count。如果head index到了一個list的臨界點(參考程式碼給的是fixedSize - 1, 但是我覺得直接用fixedSize更好理解?),以head index的node為基礎get 出一個新的list headList = (List<Object>)headList.get(head); ,把當前的headList清空,讓headList指向這個新的list,然後把head index歸零。最後,return那個記錄下來的head value。

-> 自己想的辦法:可以用一個大的list來記錄每一個list的頭,如果一個list結束了,抹去當前list,換到下一個?