LeetCode算法系列:34. Find First and Last Position of Element in Sorted Array

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82143825

题目描述:

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]

算法实现:

这个算法的本质依然是二分法,只不过分两步,第一步找到重复出现元素的最左侧index,第二步找到最右侧的index,这两步都是使用二分法,只不过改变了迭代条件等。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res;
        if(nums.empty()){
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }        
        int i = 0, j = nums.size() - 1, k;
        while(i <= j){            
            k = int((i + j)/2);
            if(i + 1 == j || i == j){
                if(nums[i] == target)res.push_back(i);
                else if(nums[j] == target)res.push_back(j);
                else res.push_back(-1);
                break;
            }
            if(nums[k] >= target) j = k;
            else i = k;
        }
        if(res[0] == -1)res.push_back(-1);
        else {
            i = res[0];
            j = nums.size() - 1;
            while(i <= j || i == j){
                k = int((i + j)/2);
                if(i + 1 == j || i == j){
                    if(nums[j] == target)res.push_back(j);
                    else if(nums[i] == target)res.push_back(i);
                    break;
                }
                if(nums[k] > target) j = k;
                else i = k;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82143825
今日推荐