[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array
Posted fish1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章