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,換到下一個?

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM