704. Binary SearchΒΆ
Using the general template,
- The search space is \([0,len(nums))\), so we initialize \(left = 0\) and \(right = len(nums)\).
- The condition is to find the minimal index \(k\) such that \(nums[k] >= target\).
- If the target exists in the array, the minimal value satisfying the condition will be
targetitself, and its index will be stored inleft.
Runtime Complexity
Time: \(O(logn)\), search space is reduced by half in each iteration
Space: \(O(1)\), constant space from variables.