LeetCode-34-Find First and Last Position of Element in Sorted Array

算法描述:

Given an array of integers nums sorted in ascending order,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].

Example 1:

Input: nums = [,target = 8
Output: [3,4]5,7,8,10]

Example 2:

Input: nums = [,target = 6
Output: [-1,-1]5,10]

解题思路:

搜索问题,运行时间限制为O(log n) 首先考虑采用二分法。找到目标值之后向两边扩展,从而获得最终的结果。

    vector<int> searchRange(vector<int>& nums,int target) {
        vector<int> results;
        int left = 0;
        int right = nums.size()-1;
        int leftIndex = -1;
        int rightIndex = -1;
        while(left <= right){
            int middle = left + (right - left) / 2;
            if(nums[middle] > target) right = middle -1;
            else if(nums[middle] < target) left = middle+1;
            else{
                leftIndex = middle;
                rightIndex = middle;
                while(leftIndex-1 >=0 && nums[leftIndex-1]==target) leftIndex--;
                
                while(rightIndex+1 <=nums.size()-1 && nums[rightIndex+1]==target) rightIndex++;
                break;
            }
        }
        results.push_back(leftIndex);
        results.push_back(rightIndex);
        return results;
    }

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效