TikTok OA 面试真题解析:Ocean View Buildings 与 Minimum Operations to Make Array Palindromic

18次阅读
没有评论

The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.

Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.

Example 1:

Input: heights = [4,2,3,1]
Output: [0,2,3]

Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.

Example 2:

Input: heights = [4,3,2,1]
Output: [0,1,2,3]

Explanation: All the buildings have an ocean view.

Example 3:

Input: heights = [1,3,2,4]
Output: [3]

Explanation: Only building 3 has an ocean view.

You are given an array nums consisting of positive integers.

You can perform the following operation on the array any number of times:

  • Choose any two adjacent elements and replace them with their sum.

For example, if nums = [1,2,3,1], you can apply one operation to make it [1,5,1].

Return the minimum number of operations needed to turn the array into a palindrome.

Example 1:

Input: nums = [4,3,2,1,2,3,1]
Output: 2

Explanation: We can turn the array into a palindrome in 2 operations as follows:

  • Apply the operation on the fourth and fifth element of the array, nums becomes equal to [4,3,2,3,3,1].
  • Apply the operation on the fifth and sixth element of the array, nums becomes equal to [4,3,2,3,4].

The array [4,3,2,3,4] is a palindrome. It can be shown that 2 is the minimum number of operations needed.

Example 2:

Input: nums = [1,2,3,4]
Output: 3

Explanation: We do the operation 3 times in any position; at the end, we obtain the array [10], which is a palindrome.

这组 TikTok 面试题考察的是经典的数组扫描与双指针 / 贪心思维。第一题“海景楼”可以从右向左遍历,维护右侧最高楼层,只有当前高度严格大于历史最高值时才拥有海景,最后再按下标升序返回即可,时间复杂度 O(n)。第二题“最少合并成回文”由于每次只能合并相邻元素且所有数为正,可以用左右双指针从两端向中间收缩:如果左右和相等就同时移动,不等时总是合并较小的一侧来拉近两边和,统计合并次数即可得到最小操作数,整体也是 O(n) 且不需要额外复杂数据结构。

正文完
 0