551.Count Comparisons in a Linear Search
Easy
A linear search checks the elements of
nums from left to right and stops at the first one equal to target. Return how many comparisons it makes — the position of the first match plus one, or the full length if the target is absent.
Time complexityTime ComplexityHow the number of steps an algorithm takes grows as the input size n grows. describes how this count grows with the input size. For the same n, different inputs need different work: one comparison in the best caseBest CaseThe input that makes an algorithm do the least work., n in the worst caseWorst CaseThe input that makes an algorithm do the most work. Big-O usually describes this case.. We usually quote the worst case, so linear search is O(n).
Example 1:
Input: nums = [8,3,5,3], target = 5
Output: 3
Example 2:
Input: nums = [8,3,5], target = 9
Output: 3
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 1000 - ●
-1000000 ≤ nums[i], target ≤ 1000000
nums =
[8, 3, 5, 3]
target =
5