当前位置:网站首页>LeetCode:34. Find the first and last positions of elements in a sorted array

LeetCode:34. Find the first and last positions of elements in a sorted array

2022-07-06 08:51:00 Bertil

Given an array of integers in ascending order nums, And a target value target. Find the start and end position of the given target value in the array .

If the target value does not exist in the array target, return [-1, -1].

Advanced :

  • You can design and implement time complexity of O(log n) Does the algorithm solve this problem ?

Example 1:

 Input :nums = [5,7,7,8,8,10], target = 8
 Output :[3,4]

Example 2:

 Input :nums = [5,7,7,8,8,10], target = 6
 Output :[-1,-1]

Example 3:

 Input :nums = [], target = 0
 Output :[-1,-1]

Tips :

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums It is a group of non decreasing numbers
  • -10^9 <= target <= 10^9

Their thinking

1. First, judge that the array is not empty and this element exists , And then use indexOf and lastIndexOf Method to find the first and last positions of the element

Code

/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var searchRange = function(nums, target) {
    
    if(nums !== [] && nums.indexOf(target) !== -1) {
    
        let left = nums.indexOf(target)
        let right = nums.lastIndexOf(target)
        return [left, right]
    }else {
    
        return [-1, -1]
    }
};
原网站

版权声明
本文为[Bertil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060844309122.html