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。