zoukankan      html  css  js  c++  java
  • LeetCode-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) {
            vector<int>fail;
            fail.push_back(-1);
            fail.push_back(-1);
            vector<int>ret;
             if(n<=0){
                return fail; 
             }
             if(n==1){
                 if(A[0]==target){
                     ret.push_back(0);
                     ret.push_back(0);
                     return ret;
                 }
                 else return fail;
             }
             int index1=-1,index2=n;
            //find the last element less than target
            int start,end;
            start=0;end=n-1;
            while(start<=end){
                int mid=(start+end)/2;
                if(A[mid]>=target){
                    end=mid-1;
                }
                else{
                    if(mid==n-1){
                        index1=mid;
                        break;
                    }
                    if(A[mid+1]>=target){
                        index1=mid;
                        break;
                    }
                    else{
                        start=mid+1;
                    }
                }
            }
            //find the first element great than target
            start=0;end=n-1;
            while(start<=end){
                int mid=(start+end)/2;
                if(A[mid]<=target){
                    start=mid+1;
                }
                else{
                    if(mid==0){
                        index2=0;
                        break;
                    }
                    else{
                        if(A[mid-1]<=target){
                            index2=mid;
                            break;
                        }
                        else{
                            end=mid-1;
                        }
                    }
                    
                }
            }
            if(index1==index2-1)return fail;
            else{
                ret.push_back(index1+1);
                ret.push_back(index2-1);
                return ret;
            }
        }
    };
    
  • 相关阅读:
    eclipse新 java 文件时自动生成注释
    int占几个字节
    eclipse常用插件
    Asp.net中IsPostBack的实现原理
    Github的入门简介
    Hypertable
    VA01/VA02行项目物料搜索帮助新增页签
    rich_text
    js之Math
    js function参数
  • 原文地址:https://www.cnblogs.com/superzrx/p/3328707.html
Copyright © 2011-2022 走看看