微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。