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

    思路1:二分查找找到等于target的位置,再寻找target的左右边界,注意别越界!

    class Solution {
    public:
       vector<int> searchRange(vector<int>& nums, int target) {
           int temp[] = { -1, -1 };
           vector<int> ret(temp, temp + 2);
           if (nums.size() == 0)
               return ret;
           int l = 0;
           int r = nums.size();
           int mid = 0;
           while (l <= r){
               mid = (l + r) / 2;
               if (nums[mid] == target)
                   break;
               else if (nums[mid]>target)
                   r = mid - 1;
               else
                   l = mid + 1;
           }
           if (nums[mid] != target){
               return ret;
           }
           l = r = mid;
           while (nums[l] == target&&l>0)
               l--;
           while (r<nums.size() && nums[r] == target)
               r++;
           if (nums[l] != target)
               l++;
           if (r>=nums.size()||nums[r] != target)//注意r可能为nums.size(),这种情况也要r--
               r--;
           ret[0] = l;
           ret[1] = r;
           return ret;
        }
    };
    思路2:类似于lower_bound和upper_bound的实现
    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int a[]={findLow(nums,target),findHigh(nums,target)};
            vector<int> ret(a,a+2);
            return ret;
        }
        int findLow(vector<int>& nums,int target){
            int l=0,r=nums.size()-1;
            while(l<=r){
                int m=(l+r)>>1;
                if(nums[m]<target)
                    l=m+1;
                else
                    r=m-1;
            }
            if(nums[l]==target)
                return l;
            return -1;
        }
        int findHigh(vector<int>& nums,int target){
            int l=0,r=nums.size()-1;
            while(l<=r){
                int m=(l+r)>>1;
                if(nums[m]>target)
                    r=m-1;
                else
                    l=m+1;
            }
            if(nums[r]==target)
                return r;
            return -1;
        }
        
    };
     
     
     
  • 相关阅读:
    静态方法中访问类的实例成员
    Java Interger类,两对整数明明完全一样,为何一个输出true,一个输出false
    使用类的静态字段和构造函数,跟踪某个类所创建对象的个数
    Java基础笔记3
    Java 统计单词频数
    重拾javaweb(假期后第一次web测试)
    人月神话读后感(三)
    人月神话读后感(二)
    人月神话读后感(一)
    七天开发安卓软件(七)
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5039456.html
Copyright © 2020-2023  润新知