競賽程式設計簡單

在幾乎排序的數組中搜索

「在幾乎排序的陣列中搜尋」問題的詳細指南和 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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。