LeetCode 34. Find First and Last Position of Element in Sorted Array

2019-07-26 11:06:29 浏览数 (1)

题目

二分练习

代码语言:javascript复制
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        
         vector<int> ans;
        if(nums.size()==0)
        {
            ans.push_back(-1);
            ans.push_back(-1);
            
            return ans;
        }
        
        int start = 0;
        int end = nums.size()-1;
        
       
        while(start<=end)
        {
            int mid = (start end)/2;
            
            if(nums[mid]>=target)
            {
                end = mid-1;
            }
            else if(nums[mid]<target)
            {
                start = mid 1;
            }
        }
        
        if(start==nums.size()||nums[start]!=target){
            ans.push_back(-1);
            ans.push_back(-1);
            
            return ans;
        }
        ans.push_back(start);
        start=0;
        end=nums.size()-1;
        
        while(start<=end)
        {
            int mid = (start end)/2;
            
            if(nums[mid]>target)
            {
                end = mid-1;
            }
            else if(nums[mid]<=target)
            {
                start = mid 1;
            }
        }
        
        ans.push_back(end);
        
        return ans;
        
        
    }
};

0 人点赞