leetcode题目例题解析(三)

leetcode题目例题解析(三)

Search for a Range

题目描述:

Given an array of integers 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].
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8
return [3, 4].

题意解析:

这道题的主要意思就是一个简单的查找,而且目标数组就已经排好序的,所以最快的办法就是用二分查找,要求中是O(log n)的复杂度,一看就知道使用二分查找,这里有一些要注意的,就是如果没有找到,就要返回-1,-1。其他地方没有什么难点和坑点。

解题思路:

直接二分查找,用两个迭代器分别代表查找的开始和结尾,保持开始>=结尾就行了

代码:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int start, end, mid;
        int len = nums.size();
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            mid = (left + right)/2;
            if (nums[mid] == target) {
                start = mid;
                end = mid;
                //这里注意不要越界,不然可能会导致错误的结果
                while(start >= 0&&nums[start] == target) start--;
                while(end < len&&nums[end] == target) end++;
                start++;
                end--;
                break;
            }
            if (nums[mid] > target) {
                right = mid - 1;
            }
            if (nums[mid] < target) {
                left = mid + 1;
            }
        }
        if (left > right)
            start = end = -1;
        vector<int> res;
        res.push_back(start);
        res.push_back(end);
        return res;
    }
};

原题目链接:
https://leetcode.com/problems/search-for-a-range/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78058346