14 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]

还是用两头逼近的老办法,处理特殊情况的部分有点难看,不过程序运行的结果很不错,就不参考大神做法了。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        
        vector<int> ans = {-1,-1};
        
        int len = nums.size();
        
        if(len < 1) return ans;
        
        if(len == 1){
            
            if(nums[0] == target)
            {
                ans[0] = 0;
                ans[1] = 0;
                return ans;
                
            }
            else return ans;
        }
        
    
        int left = 0;
        int right = nums.size() - 1;
        
        if(target < nums[left]) return ans;
        if(target > nums[right]) return ans;
        
        bool l = false;
        bool r = false;
        
        while(left < right)
        {            
            
            if(nums[left]  < target) left++;
            if(nums[right] > target) right--;
            
            
            if(nums[left] == target){
                 ans[0] = left;
                 l = true;
            }
            
            if(nums[right] == target){
                ans[1] = right;
                r = true;
            } 
            
            
            if(l&&r) break;

        }
        
        
        return ans;
        
    }
};
posted @ 2019-08-20 22:14  孙小鸟  阅读(70)  评论(0编辑  收藏  举报