独角兽公司电话面试 Coding 题目的解答 2019-June
前提假设是 两边 边界, 有无穷高的墙.
这里是完整的代码和输出示例.
# Time: max(A) * len(A) # Space: O(1) def fill_slot(B, curt): if not B: return n = len(B) i = curt while i > 0 and B[i - 1] <= B[i]: i -= 1 left, left_low = i, B[i] i = curt while i < n - 1 and B[i + 1] <= B[i]: i += 1 right, right_low = i, B[i] if left_low <= right_low: B[left] += 1 return B[right] += 1 def print_hist(A, position, qty): B = A[:] print(A) for _ in range(qty): fill_slot(B, position) print(B) height = max(B) n = len(B) for h in range(height, 0, -1): line = [] for i in range(n): if h > B[i]: line.append(" ") print(" ", end = " ") elif A[i] < h <= B[i]: line.append("o") print("o", end = " ") elif h <= A[i]: line.append("x") print("x", end = " ") print("", end = "\n") # print(" ".join(line)) print(" ".join([str(i) for i in range(n)]))
A = [7,1,3,1,0,4,1,0] print_hist(A, 5, 4) print_hist(A, 5, 9)
print_hist(A, 4, 9)
输出 - print_hist(A, 5, 4)
[7, 1, 3, 1, 0, 4, 1, 0] [7, 1, 3, 1, 1, 4, 1, 0] [7, 1, 3, 1, 1, 4, 1, 1] [7, 1, 3, 2, 1, 4, 1, 1] [7, 1, 3, 2, 2, 4, 1, 1] x x x x x x x x x x o o x x x x x o x x o 0 1 2 3 4 5 6 7
输出 - print_hist(A, 5, 9)
[7, 1, 3, 1, 0, 4, 1, 0] [7, 1, 3, 1, 1, 4, 1, 0] [7, 1, 3, 1, 1, 4, 1, 1] [7, 1, 3, 2, 1, 4, 1, 1] [7, 1, 3, 2, 2, 4, 1, 1] [7, 1, 3, 2, 2, 4, 1, 2] [7, 1, 3, 2, 2, 4, 2, 2] [7, 1, 3, 3, 2, 4, 2, 2] [7, 1, 3, 3, 3, 4, 2, 2] [7, 2, 3, 3, 3, 4, 2, 2] x x x x x x x o o x x o x o o x o o x x x x o x x o 0 1 2 3 4 5 6 7
print_hist(A, 4, 9)
[7, 1, 3, 1, 0, 4, 1, 0] [7, 1, 3, 1, 1, 4, 1, 0] [7, 1, 3, 2, 1, 4, 1, 0] [7, 1, 3, 2, 2, 4, 1, 0] [7, 1, 3, 3, 2, 4, 1, 0] [7, 1, 3, 3, 3, 4, 1, 0] [7, 2, 3, 3, 3, 4, 1, 0] [7, 3, 3, 3, 3, 4, 1, 0] [7, 4, 3, 3, 3, 4, 1, 0] [7, 4, 4, 3, 3, 4, 1, 0] x x x x o o x x o x o o x x o x o o x x x x x o x x 0 1 2 3 4 5 6 7