Sekcja DSAŁatwe

Wyszukiwanie liniowe

Szczegółowy przewodnik i implementacja Python dla problemu „Wyszukiwanie liniowe”.

Oświadczenie o problemie

Łatwe

Napisz funkcję linear_search(arr, target), która pobiera listę liczb całkowitych arr i liczbę całkowitą target. Skanuje listę od początku do końca i zwraca indeks oparty na 0 pierwszym wystąpieniu target. Jeśli na liście nie ma target, zwróć -1.

Ograniczenia
  • 0 <= len(arr) <= 1000
  • -10^9 <= arr[i], target <= 10^9

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla wyszukiwania, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

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

Otwórz w Edytorze
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

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.