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; } };
原文地址:https://www.cnblogs.com/fish1996/p/11335475.html
时间: 2024-10-10 01:46:46