zoukankan      html  css  js  c++  java
  • leetcode------Search for a Range

    标题: Search for a Range
    通过率: 27.7%
    难度: 中等

    Given a sorted array of integers, 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].

    For example,
    Given [5, 7, 7, 8, 8, 10] and target value 8,
    return [3, 4].

    本题就是对应target的开始和结束位置,二分法查找。每次比较下开始位置和结束位置,那么开始结束位置的初始值要设定好,

    开始位置设定成数组的最大位置。结束位置设定成0,,最后验证下对应位置是不是target,如果不是那就将数组置-1

    代码如下:

     1 public class Solution {
     2     public int[] searchRange(int[] A, int target) {
     3         int res []={A.length-1,0};
     4         bs(A,target,0,A.length-1,res);
     5         if(A[res[0]]!=target){
     6             res[0]=-1;
     7             res[1]=-1;
     8         }
     9         return res;
    10     }
    11     public void bs(int[] A,int target,int start,int end,int [] res){
    12         if(start<=end){
    13         int mid=(start+end)/2;
    14         if(A[mid]==target){
    15             if(mid<res[0])res[0]=mid;
    16             if(mid>res[1])res[1]=mid;
    17         }
    18         bs(A,target,start,mid-1,res);
    19         bs(A,target,mid+1,end,res);
    20         }
    21     }
    22 }
  • 相关阅读:
    Java反射
    安装python
    查看网页加载速度,并优化
    模型按一个圈摆放(10等分)
    y = n*x 匀速,变速运动
    物体绕圆形做圆周运动
    three.js 相机跟随鼠标移动
    three.js 物体随鼠标移动
    three.js 画正多边形-线性
    ES6的JavaScript数据结构实现之队列
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4366949.html
Copyright © 2011-2022 走看看