[34][1]我在做一个leetcode问题
我想到了一个解决办法
function firstAndLastOccurenceOfElement(arr, key, start, end){
let mid = Math.floor((start + end)/2)
if(start > end){
return -1;
}
if(arr[mid] === key){
firstOccurence = mid;
lastOccurence = mid;
let checkFirstOccurence = firstAndLastOccurenceOfElement(arr, key,start, mid -1)
if(checkFirstOccurence < firstOccurence){
firstOccurence =checkFirstOccurence
}
let checkLastOccurence = firstAndLastOccurenceOfElement(arr, key,mid +1, end)
if(checkLastOccurence > lastOccurence){
lastOccurence = checkLastOccurence
}
return [firstOccurence, lastOccurence]
}
if(arr[mid] > key){
return firstAndLastOccurenceOfElement(arr, key, start, mid - 1)
}
if(arr[mid] < key){
return firstAndLastOccurenceOfElement(arr, key, mid + 1 , end)
}
return -1;
}
let arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9];
let key = 5;
console.log(firstAndLastOccurenceOfElement(arr, key, 0, arr.length - 1));
但是这个函数并没有找到第一个索引。对于上面的输入,它给出了如下的结果:
[-1, 3]
我试过调试,但没有什么给予。这里出了什么问题?[1]:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
1条答案
按热度按时间wgx48brx1#
飞镖解决方案