leetcode--34. Search for a Range

Given a sorted array of integers, 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].

题目大意:给定一个排序的数组和一个目标数,寻找该目标数在数组中出现的首尾位置。如题中例子,8在数组中是第3、4个。

思路:排序数组->二分查找。如果nums[mid] > target 那么end需要变为mid-1;如果nums[mid] < target,那么begin需要变为mid+1;如果nums[mid]==target,那么首尾值肯定是在左右两边,注意边界处理。

class Solution {
public:
    vector searchRange(vector& nums, int target) {
        int begin = 0;
        int end = nums.size()-1;
        vector result;
        
        while(nums[begin] <= nums[end]){
           int mid = (begin+end)/2; 
           if(nums[mid] == target){
                begin = mid ; 
                while(nums[begin] == target && begin>=0){
                    --begin;
                }
                result.push_back(begin+1);
                end = mid;
                while(nums[end] == target && end <= nums.size()-1){
                    ++end;
                }
                result.push_back(end-1);
                return result;
            }
            else if(nums[mid] < target){
                begin = mid + 1;
            }
            else if(nums[mid] > target){
                end = mid -1;
            }
        }
        result.push_back(-1);
        result.push_back(-1);
        return result;
    }
};

leetcode编译通过。

你可能感兴趣的:(数据结构与算法)