Find First and Last Position of Element in Sorted Array
Posted tianzeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find First and Last Position of Element in Sorted Array相关的知识,希望对你有一定的参考价值。
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]
code
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res{-1,-1}; if(nums.empty()||nums.size()<0||nums.at(0)>target||target>nums.at(nums.size()-1)) return res; int low=0; int height=nums.size()-1; int pos=-1; while(low<=height) { int mid=(low+height)/2; if(nums.at(mid)==target) { pos=mid; break; } if(target<nums.at(mid)) height=mid-1; else low=mid+1; } if(pos==-1) return res; int i=1; int j=1; bool flag1=true; bool flag2=true; while(flag1||flag2) { if(pos-i>=0&&nums.at(pos-i)==target) ++i; else flag1=false; if(pos+j<nums.size()&&nums.at(pos+j)==target) ++j; else flag2=false; } res.at(0)=pos-(i-1); res.at(1)=pos+(j-1); return res; } }; int main() { vector<int> arr; Solution s; vector<int> res(s.searchRange(arr,1)); for(auto i:res) cout<<i<<" "; cout<<endl; return 0; }
code2
vector<int> searchRange(vector<int>& nums, int target) { int start = 0, end = nums.size(), mid, left, right; while (start < end) { mid = (start + end) / 2; if (nums[mid] >= target) end = mid; else start = mid + 1; } left = start; start = 0, end = nums.size(); while (start < end) { mid = (start + end) / 2; if (nums[mid] > target) end = mid; else start = mid + 1; } right = start; return left == right ? vector<int> {-1,-1} : vector<int> {left,right-1}; }
以上是关于Find First and Last Position of Element in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 34. Find First and Last Position of Element in Sorted Array
Find First and Last Position of Element in Sorted Array
[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array
[leetcode][34] Find First and Last Position of Element in Sorted Array
34- Find First and Last Position of Element in Sorted Array
LeetCode找元素Find First and Last Position of Element in Sorted Array