leetcode 34. Find First and Last Position of Element in Sorted Array

*爱你&永不变心* 提交于 2019-12-15 14:25:03

又是二分查找

var searchRange = function (nums, target) {
      var left = 0, right = nums.length - 1;
      while (left <= right) {
        var mid = left + ((right - left) >> 1);
        if (nums[mid] == target) { //开始三个分支的处理
          var begin = mid
          while (nums[begin - 1] == target) {
            --begin
          }
          var end = mid
          while (nums[end + 1] == target) {
            ++end
          }
          return [begin, end]
          break
        } else if (nums[mid] < target) {//[1,2,3,4,5,6,7], mid = 4, target = 5
          left = mid + 1//left只能往mid靠
        } else {
          right = mid - 1//right只能往mid靠
        }
      }
      return [-1, -1]
    };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!