[LeetCode] 34. Find First and Last Position of Element in Sorted Array
在有序数组中查找元素的第一个和最后一个位置。题意很简单,给了一个数组和一个数字A,问数字A第一次和最后一次在数组中出现的位置在哪里,若没有,return -1。例子,
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]
也是一道典型的二分法题目,思路是通过二分法思想分别找到第一个插入的位置和第二个插入的位置。
时间O(log n)
空间O(1)
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var searchRange = function(nums, target) { // corner case if (nums === null || nums.length === 0) { return [-1, -1]; } // normal case let start = findFirst(nums, target); if (start === -1) { return [-1, -1]; } let end = findLast(nums, target); return [start, end]; }; var findFirst = function(nums, target) { let start = 0; let end = nums.length - 1; while (start + 1 < end) { let mid = Math.floor(start + (end - start) / 2); if (nums[mid] < target) { start = mid; } else { end = mid; } } if (nums[start] === target) return start; if (nums[end] === target) return end; return -1; }; var findLast = function(nums, target) { let start = 0; let end = nums.length - 1; while (start + 1 < end) { let mid = Math.floor(start + (end - start) / 2); if (nums[mid] > target) { end = mid; } else { start = mid; } } if (nums[end] === target) return end; if (nums[start] === target) return start; return -1; };
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28