Given a sorted array of integers nums and an integer target, write a function to search for target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
O(log n) runtime complexity.1 <= nums.length <= 10^4-10^4 <= nums[i], target <= 10^4nums are unique.nums is sorted in ascending order.nums are unique.The problem requires an O(log n) runtime complexity, which is a strong indication to use the Binary Search algorithm. Here’s how the binary search will work in this context:
left and right, to represent the search interval’s boundaries.
left initially pointing to the first index (0).right initially pointing to the last index (nums.length - 1).left is less than or equal to right):
mid as (left + right) / 2.mid with the target:
nums[mid] equals target, return mid.nums[mid] is less than target, move the left pointer to mid + 1 (search in the right subarray).nums[mid] is greater than target, move the right pointer to mid - 1 (search in the left subarray).target, return -1.public class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // prevents overflow more safely than (left + right) / 2
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Target not found
}
}
The time complexity of the binary search algorithm is O(log n) due to the following:
The space complexity is O(1) as we are only using a constant amount of extra space for variables left, right, and mid.
This completes the explanation and solution for the binary search algorithm in Java to solve the given problem on LeetCode.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?