What if we assume the Ray Not Reflected and Keeps Going?
Consider that there is a mirrored world behind the mirror, we can expand the room behind the mirror. The ray has not been reflected and keep going cross the room.
As the image below shows, we can easily know which receptor will the ray will meet first.
Here shows 2 Approaches to slove this problem: Brute Force and Binary Search.
Brute Force
The easiest method is scan the array from left to right. Use two variables to record the index of the first and last element \(\textit{target}\). The time complexity is \(O(n)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicstaticint[] searchRange(int[] nums, int target) { int[] ans = {-1, -1}; intlen= nums.length; for (inti=0; i < len; i++) { if (nums[i] == target && ans[0] == -1) { ans[0] = i; } elseif (nums[i] > target && ans[0] >= 0) { ans[1] = i - 1; return ans; } }
if (ans[0] >= 0) { ans[1] = len - 1; }
return ans; }
Analysis
Time Complexity: \(O(n)\)
Space Complexity: \(O(1)\)
Binary Search
Since the array is sorted in ascending order, so we can binary search to speed up the search.
Considering the start and end positions of target, in fact, what we are looking for is “the first position in the array equal to target” (recorded as \(\textit{leftIdx}\) ) and “the first position greater than The position of target minus one” (recorded as \(\textit{rightIdx}\) ).
In binary search, looking for \(\textit{leftIdx}\) is to find the first index greater than or equal to target in the array, and looking for \(\textit{rightIdx}\) is to find the first index greater than target in the array index of target, then decrement the index by one.
Finally, since \(\textit{target}\) may not exist in the array, we need to re-check the two indices we got \(\textit{leftIdx}\) and \(\textit{rightIdx}\) to see if they meet the conditions, if so It returns \([\textit{leftIdx}, \textit{rightIdx}]\), if it does not match, it returns \([-1, -1]\).