DSA 部分簡單

線性搜尋

“線性搜尋”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 linear_search(arr, target),它接受整數 arr 和整數 target 的列表。它從頭到尾掃描清單並傳回 target 第一次出現的從 0 開始的索引。如果清單中不存在 target,則傳回 -1

約束條件
  • 0 <= len(arr) <= 1000
  • -10^9 <= arr[i], target <= 10^9

範例

Example 1
Input
arr = [4, 2, 9, 1, 7], target = 9
Output
2
Explanation

The target 9 is found at index 2 of the list [4, 2, 9, 1, 7].

Example 2
Input
arr = [4, 2, 9, 1, 7], target = 5
Output
-1
Explanation

The target 5 is not present in the list, so we return -1.

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 資源

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