码迷,mamicode.com
首页 > 其他好文 > 详细

[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array

时间:2019-08-11 17:32:43      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:array   vector   sort   sorted   range   arc   tor   pos   搜索   

problem:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

        经典二分搜索题。要点是改变low或high的时候把当前数字mid也包含进来,因为它也可能是结果。

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

 

[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array

标签:array   vector   sort   sorted   range   arc   tor   pos   搜索   

原文地址:https://www.cnblogs.com/fish1996/p/11335475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!