竞争性编程简单

在几乎排序的数组中搜索

“在几乎排序的数组中搜索”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 search_almost_sorted(arr, target),在几乎排序的数组 arr 中搜索 target 值。几乎排序的数组是这样一种数组,其中应位于完全排序数组中索引 i 处的元素可以位于索引 i-1ii+1 处。如果找到则返回目标的从 0 开始的索引,否则返回 -1。

约束条件
  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i], target <= 10^9
  • All elements in arr are unique.

示例

Example 1
Input
search_almost_sorted([10, 3, 40, 20, 50, 80, 70], 40)
Output
2
Explanation

40 is at index 2 (which is its correct position in a fully sorted version).

Example 2
Input
search_almost_sorted([10, 3, 40, 20, 50, 80, 70], 90)
Output
-1
Explanation

90 does not exist in the array.

Need a Hint?
考虑使用特定于搜索和排序的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。