Find First Occurrence in Sorted Array
In many data processing systems, efficiently locating specific data points within large, sorted datasets is crucial. Imagine a system that logs sensor readings over time, and these readings are stored in a sorted array. We need a way to quickly find the first instance of a particular reading to analyze its initial impact or to start processing from that point onwards.
Implement a function findFirstOccurrence that takes a sorted array of numbers nums and a target number. Your function should return the index of the first occurrence of target in nums. If the target is not found, return -1.
nums: A number[] representing a non-decreasingly sorted array of integers.target: A number representing the integer to search for.number which is the 0-based index of the first occurrence of target in nums. If target is not present, return -1.nums is guaranteed to be sorted in non-decreasing order.nums may contain duplicate values. You must return the index of the first such occurrence.nums is empty, the target cannot be found, so return -1.Examples
Example 1
Input:
nums = [1, 2, 3, 3, 3, 4, 5], target = 3
Output:
2
Note:
The number 3 appears at indices 2, 3, and 4. The first occurrence is at index 2.
Example 2
Input:
nums = [1, 2, 3, 4, 5], target = 6
Output:
-1
Note:
The target 6 is not present in the array.
Example 3
Input:
nums = [5, 5, 5, 5], target = 5
Output:
0
Note:
The target 5 appears multiple times. The first occurrence is at index 0.
Example 4
Input:
nums = [], target = 7
Output:
-1
Note:
The array is empty, so the target cannot be found.
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9nums is sorted in non-decreasing order.Loading editor...