Linear Search
Intuition
The simplest approach is to iterate through the array and check each element. Although this does not take advantage of the sorted property and runs in linear time, it is straightforward and always correct. For small arrays this may be sufficient, but it does not meet the O(log n) requirement for larger inputs.
Algorithm
- Iterate through each element of the array from index 0 to n - 1.
- If the current element equals the target, return the current index.
- If the loop completes without finding the target, return -1.
O(n)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int search(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
};class Solution {
public int search(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
}def search(nums: list[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target:
return i
return -1func search(nums []int, target int) int {
for i, num := range nums {
if num == target {
return i
}
}
return -1
}