← 返回 google 的题目列表Implement Binary Search (easy variant)
类型:online_judge
Problem: Implement Binary Search (easy)
Given an integer array nums sorted in ascending order (possibly empty) and an integer target, search for target in the array:
If target exists in nums, return its index (0-based).
Otherwise, return -1.
Requirements
Time complexity: O(log n)
Space complexity: O(1)
Input format (stdin)
Line 1: an integer n, the length of the array
Line 2: n integers representing nums (sorted ascending)
Line 3: an integer target
Output format (stdout)
Print one integer: the index of target, or -1.
Constraints
0 <= n <= 2 * 10^5
nums is strictly increasing (no duplicates)
nums[i] and target fit in 32-bit signed integers
Example
Input:
5
1 3 5 7 9
7
Output:
3
Note: The original post only mentioned a “super easy binary search” without specifying the exact variant; this is the standard form.
Example
Input
5
1 3 5 7 9
7
Output
3