简体   繁体   English

在排序数组中查找元素的第一个和最后一个 Position

[英]Find First and Last Position of Element in Sorted Array

I am trying to solve the LeetCode problem Find First and Last Position of Element in Sorted Array :我正在尝试解决 LeetCode 问题Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.给定一个按升序排列的整数数组nums ,找到给定target的开始和结束 position。

If target is not found in the array, return [-1, -1] .如果在数组中找不到target ,则返回[-1, -1]

You must write an algorithm with O(log n) runtime complexity.您必须编写具有O(log n)运行时复杂度的算法。

I am writing this code:我正在写这段代码:

var searchRange = function(nums, target) {
  nums = nums.sort((a, b) => (a-b))
  let result = [];
  for(let i = 0; i < nums.length; i++) {
    if (nums[i] == target) {
      result.push(i)
    } else {
     result = [-1, -1]
    }
  }

  return result
};
 
console.log(searchRange([5,7,7,8,8,10], 8));

It should return:它应该返回:

[3, 4]

but it returns:但它返回:

[-1, -1]

What is wrong?怎么了?

You loop does not have a good exit condition.你的循环没有一个好的退出条件。 Loop iterates till the last element and if the last element does not match, it sets -1,-1 into the result.循环迭代直到最后一个元素,如果最后一个元素不匹配,则将 -1,-1 设置为结果。 Intermediate values of result are ignored.结果的中间值被忽略。

Other problems:其他问题:

  • You're given a sorted array, so don't sort it again.你得到一个排序的数组,所以不要再次排序。 That's heavy.那很重。
  • When you iterate over all elements, it has O(n) time complexity.当您迭代所有元素时,它的时间复杂度为 O(n)。

Solution:解决方案:

  • Binary search to find any one occurence of the element - save the index where the value is found.二进制搜索以查找元素的任何一次出现 - 保存找到该值的索引。
  • Use the index found to check left and right adjacent elements in the original array to find the start and end positions.使用找到的索引检查原始数组中左右相邻的元素,以找到开始和结束位置。

Your else code is wiping out results from the previous iteration of the loop.您的else代码正在清除循环的前一次迭代的结果。

However, your code is not efficient:但是,您的代码效率不高:

First, it calls sort on an array that is given to be already sorted: so leave that out.首先,它对一个已经排序的数组调用sort :所以把它排除在外。

Secondly, as your code is visiting every element in the array, you still get a time complexity of O(n), not O(logn).其次,当您的代码访问数组中的每个元素时,您仍然会得到 O(n) 的时间复杂度,而不是 O(logn)。

To get O(logn) you should implement a binary search, and then perform a search to find the start of the range, and another to find the end of it.要获得 O(logn),您应该实现二进制搜索,然后执行搜索以找到范围的开头,再执行搜索以找到范围的结尾。

Here is how that could work:这是如何工作的:

 function binarySearch(nums, target) { let low = 0; let high = nums.length; while (low < high) { let mid = (low + high) >> 1; // half way if (nums[mid] > target) { high = mid; } else { low = mid + 1; } } return high; // first index AFTER target } function searchRange(nums, target) { let end = binarySearch(nums, target); let start = binarySearch(nums, target - 1); return start === end ? [-1, -1] : [start, end - 1]; } console.log(searchRange([5,7,7,8,8,10], 8));

 function searchRange(r,n){ var s = r.sort((a,b)=>ab); return [s.indexOf(n), s.lastIndexOf(n)]; } console.log('result 1',searchRange([5,7,7,8,8,10], 8)) console.log('result 2',searchRange([5,7,7,6,6,10], 8))

You were on the right track, its just your logic.你在正确的轨道上,这只是你的逻辑。 You are setting result to [-1, -1] if ANY index of nums after the last target index is not equal to the target .要设置result为[-1,-1]如果任何指标nums最后后target指标不等于target So you want to have the check outside of the for loop.所以你想在for循环之外进行检查。

var searchRange = function(nums, target) {
    nums = nums.sort((a, b) => (a-b));
    let result = [];
    for(let i = 0; i < nums.length; i++) {
        if (nums[i] == target) {
            result.push(i);
        }
    }

    return (result.length == 0) ? [-1, -1] : result;
};
 
 console.log(searchRange([5,7,7,8,8,10], 8));

Note: This will not be the final solution because this will return EVERY index that contains target注意:这不是最终的解决方案,因为这将返回包含target每个索引

Dart Dart

   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