javascript O(logn)时间复杂度为O(logn)的二分查找算法

qqrboqgw  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(136)

[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/

wgx48brx

wgx48brx1#

飞镖解决方案

class Solution {
  List<int> searchRange(List<int> nums, int target) {
    if (nums.isEmpty || !nums.contains(target)) {
      return [-1, -1];
    } else {
      return [nums.indexOf(target), nums.lastIndexOf(target)];
    }
  }
}

相关问题