Can searching an array with for loop without decreasing the array length me O(n) time?

Viewed 23

I am currently solving coding problems on leetcode and ran into a problem solution I don't really understand. We are meant to return the index of a target inside non-decreasing ordered integer array with distinct numbers. If the array does not include the target, we return the index it should be in. The constraint for the function is, that it should run in O(logn) time. So I kept thinking about some divide and conquer way to do it but then saw this solution:

var searchInsert = function(nums, target) {
    for (i = 0; i<nums.length; i++) {
        if (nums[i] >= target) {
            return i
        }
    }
    return nums.length
};

How is this O(logn)? Isn't the worst case that the target is the array maximum and we, therefor, iterate over the whole array?

0 Answers
Related