• [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 ofO(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,能够在O(lgn)时间完毕。

    假设数组中有target,当发现target后,对前后的内容继续用二分法 查找这种位置pos 。

    1. 前面的pos须要满足 A[pos] < target && A[pos+1] == target. pos+1即是開始位置。
    2. 后面的pos须要满足 A[pos] > target && A[pos-1] == target . pos-1是结束位置。


    代码:

    vector<int> searchRange(int A[], int n, int target) {   //C++
            vector<int> result(2);
            
            int low = 0, high = n-1;
            int mid, begin = -1, end = -1;
            while(low <= high)
            {
                mid = (low+high)/2;
                if(A[mid] > target)
                    high = mid - 1;
                else if(A[mid] < target)
                    low = mid + 1;
                else 
                {
                        begin = mid;
                        end = mid;
                        
                        //get begin
                        if(low <= begin -1){
                            while((low <= begin-1) && !(A[low]<target && A[low+1] == target) )
                            {
                                mid = (low + begin-1)/2;
                                if(A[mid] < target)
                                    low = mid+1;
                                else begin = mid;
                            }
                            if(A[low]<target && A[low+1] == target)
                                begin = low+1;
                        }
                        //get end
                        if(high >= end+1){
                            while((high >= end+1) &&!(A[high]>target && A[high-1] == target))
                            {
                                mid = (high + end +1)/2;
                                if(A[mid] > target)
                                    high = mid - 1;
                                else end = mid;
                            }
                            if(A[high]>target && A[high-1] == target)
                                end = high - 1;
                        }
                        break;
                        
                }
            }
            result[0] = begin;
            result[1] = end;
            return result;
        }


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    一个小程序的经验总结
    my favorite computer publishers
    关于在天涯看小说
    书店
    Server 2003&Windows 7&Server 2008 R2&Visual Studio&MSDN: my personal best practice
    Google搜索:基本语法
    【我喜欢的一篇文章】Fire And Motion
    Windbg学习笔记(1)
    如何清除Help Viewer 2.0之Filter Contents中的列表内容
    5年了,难道我真的不适合做一个程序员吗,请告诉我我该怎么做?
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4848858.html
Copyright © 2020-2023  润新知