Find the elements in an ordered array, the first and last position. Meaning of the questions is very simple, to an array A and a digital, ask where to position A digital first and last appearance in the array in, if not, return -1. example,
Example 1:Input: nums = [5,7,7,8,8,10], target = 8Output: [3,4]
Example 2:Input: nums = [5,7,7,8,8,10], target = 6Output: [-1,-1]
Is a typical dichotomy problem, the idea is to find the first insertion position and the second position by the insertion of ideological dichotomy respectively.
Time O (log n)
Space O (1)
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var searchRange = function(nums, target) { 7 // corner case 8 if (nums === null || nums.length === 0) { 9 return [-1, -1]; 10 } 11 // normal case 12 let start = findFirst(nums, target); 13 if (start === -1) { 14 return [-1, -1]; 15 } 16 let end = findLast(nums, target); 17 return [start, end]; 18 }; 19 20 var findFirst = function(nums, target) { 21 let start = 0; 22 let end = nums.length - 1; 23 while (start + 1 < end) { 24 let mid = Math.floor(start + (end - start) / 2); 25 if (nums[mid] < target) { 26 start = mid; 27 } else { 28 end = mid; 29 } 30 } 31 if (nums[start] === target) return start; 32 if (nums[end] === target) return end; 33 return -1; 34 }; 35 36 var findLast = function(nums, target) { 37 let start = 0; 38 let end = nums.length - 1; 39 while (start + 1 < end) { 40 let mid = Math.floor(start + (end - start) / 2); 41 if (nums[mid] > target) { 42 end = mid; 43 } else { 44 start = mid; 45 } 46 } 47 if (nums[end] === target) return end; 48 if (nums[start] === target) return start; 49 return -1; 50 };