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 = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

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

解题思路:

搜索问题,运行时间限制为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;
    }

 

posted on 2019-01-26 10:03  无名路人甲  阅读(100)  评论(0编辑  收藏  举报