美文网首页leetcode --- js版本
leetcode-medium-16期-Find First a

leetcode-medium-16期-Find First a

作者: 石头说钱 | 来源:发表于2019-03-14 23:45 被阅读0次

题目

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].

在一个升序的数组中,找出等于给定目标值首次出现后最后一次出现的位置,复杂度为O(log n),若果没有等于目标值的就返回[-1,-1]

  • 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 = [1,2,3,4], target = 3
Output: [2,2]

var searchRange = function(nums, target) {
    if(nums.length === 0){
    return [-1,-1]
  }
  let left = 0;
  let right = nums.length - 1;
  let mid = Math.floor((left+ right)/2)
  while(left <= right){
    if(target === nums[mid]){ 
      break 
    }
    if(target < nums[mid]){ 
      right = mid - 1
    }else if( target > nums[mid]){
      left =  mid + 1
    }
    mid = Math.floor((left+ right)/2)
  }
  if(target != nums[mid]){ return [-1,-1] }

  //执行到这里说明至少有一个中间值等于target,接下来进行判断左右两边是否还有相等的
  let sta = mid
  let end = mid

  //不断重复判断,是因为有可能数组全部的元素都等于target,而我们要得到首尾出现的位置
  while(sta >=0 || end < nums.length){
    var flag = false
    if(sta > 0 && nums[sta -  1] === target){
      sta--
      flag = true
    }
    if(end < nums.length -1 && nums[end + 1]===target){
      end++
      flag = true
    }
    if(!flag) break
  }
  return [sta,end]
};

相关文章

网友评论

    本文标题:leetcode-medium-16期-Find First a

    本文链接:https://www.haomeiwen.com/subject/ieqkmqtx.html