简体   繁体   English

使用二进制搜索递归地查找 O(logn) 中排序数组中元素的第一次和最后一次出现

[英]Finding first and last occurence of an element in a sorted array in O(logn) using binary search recursively

I am doing a leetcode question [34][1]我在做一道 leetcode 题 [34][1]

I came up with a solution我想出了一个解决方案

 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));

But this somehow doesn't find the first index.但这不知何故找不到第一个索引。 For the above input it gives something like:对于上面的输入,它给出了类似的东西:

[-1, 3]

I tried debugging but it didn't really give me much.我试过调试,但它并没有给我带来太多帮助。 What's wrong here?这里出了什么问题? [1]: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ [1]: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

Dart Solution Dart 解决方案

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)];
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM