12/14/2018 Airbnb的面試反思


1. 第一題 用了quick select算法

Quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quick sort sorting algorithm.

The algorithm is similar to QuickSort. The difference is, instead of recurring for both sides (after finding pivot), it recurs only for the part that contains the k-th smallest element. The logic is simple, if index of partitioned element is more than k, then we recur for left part. If index is same as k, we have foudn the k-th smallest element and we return. If index is less than k, then we recur for right part. This reduces the expected complexity from O(n logn) to O(n), with a worst case of O(n^2).

假代碼:

function quickSelect(list, left, right, k)

  if left = right

    return list[left]

  select a pivot index between left and right

  pivotIndex = partition(list, left, right, pivotIndex)

  if k = pivotIndex

    return list[k]

  else if k < pivotIndex

    right = pivotIndex - 1

  else

    left = pivotIndex + 1

 

/* 余下的task:

  1. 比較quick sort和quick select sort。相同點和不同點。

  2. 寫面試第一題的解法。

*/

 

2. 第二題 倒水 leetcode改版題

1. 先給一個array of land,要求把這個land打印出來。通過找最高的land,給每個格子計算space,再打印,來完成。

2. leetcode原題,倒水,給左邊優先權。改動:左右兩邊都是深淵。所以要在最后部分確認。會達到最后部分是因為不能往下流了,只能流到深淵里去,或者停留在原地。所以這個時候要確認兩邊是不是有一邊是平原。只要任意一邊是平原,就直接讓水流走。

3. 還有一個不一樣,就是因為要求把水打印出來,就要用另外一個array來記錄在每個index上水的高度。然后再改進一下print的算法,就可以print both water and land了。

4. 寫代碼用多個index的時候,一定要想清楚,應該用哪個index。

5. 邊界條件,比如array index out of bound。 

 


免責聲明!

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



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