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.
nums?nums be?Input: nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
Input: nums = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1
nums is sorted in ascending order.nums can be up to (10^4) elements.nums can range between (-10^4) to (10^4).To solve this problem using binary search, follow these steps:
left at the beginning of the array and right at the end of the array.left is less than or equal to right, do the following:
mid index.target value.target, return the mid index.target, move the left pointer to mid + 1.target, move the right pointer to mid - 1.target is not found, return -1.#include <vector>
class Solution {
public:
int search(std::vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
};
n is the number of elements in nums. The binary search algorithm divides the search interval in half with each iteration.This solution efficiently searches the sorted array for the target value using the binary search algorithm and meets the required O(log n) runtime complexity.
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?