1. Linear Search
Intuition
Iterate through each index i from 0 to n-1. If nums[i] == target, return index i immediately. If the loop completes without finding target, return -1.
When to apply: Useful as an initial benchmark or when the array is very small and unsorted.
Algorithm
- Step 1: Iterate index i from 0 to nums.length - 1.
- Step 2: Check if nums[i] equals target.
- Step 3: If equal, return i.
- Step 4: If loop finishes without match, return -1.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int search(vector<int>& nums, int target) { for (int i = 0; i < (int)nums.size(); ++i) { if (nums[i] == target) return i; } return -1; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— In the worst case, we inspect all n elements of the array sequentially. - Space complexity:
O(1)— Only a single index variable is maintained, requiring O(1) auxiliary space.