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

    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].

    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) 
        {
            int left=searchleft(A,0,n-1,target);
            int right=searchright(A,0,n-1,target);
            vector<int> v;
            v.push_back(left);
            v.push_back(right);
            return v;
        }
        int searchleft(int A[],int l,int r,int target)
        {
            if(l>r) return -1;
            int m=(l+r)/2;
            if(A[m]==target)
            {
                int index=searchleft(A,l,m-1,target);
                if(index==-1)   return m;
                else return index;
            }
            else if(A[m]>target) return searchleft(A,l,m-1,target);
            else return searchleft(A,m+1,r,target);
        }
        int searchright(int A[],int l,int r,int target)
        {
            if(l>r) return -1;
            int m=(l+r)/2;
            if(A[m]==target)
            {
                int index=searchright(A,m+1,r,target);
                if(index==-1)   return m;
                else return index;
            }
            else if(A[m]>target) return searchright(A,l,m-1,target);
            else return searchright(A,m+1,r,target);
        }
    }; 
  • 相关阅读:
    python之路1:介绍和入门
    SpringMVC学习指南【笔记3】基于注解的控制器
    SpringMVC学习指南【笔记2】简介、校验器、配置
    SpringMVC学习指南【笔记1】创建bean实例的方法和依赖注入
    2018-12-18笔记
    elastic-job简介
    Java中由于数据太大自动转换成科学计数法解决方式
    Redis主从复制
    Redis数据类型
    Redis的基本命令
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759326.html
Copyright © 2011-2022 走看看