一、 问题描述
Leecode第三十四题,题目为:
Given an array of integers 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]
问题理解为:
说明:
二、算法思路
1、
2、
三、实现代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//vector<int> res;
int a=0;
int b=0;
int i=0;
if (nums.empty())
a=-1;
b=-1;
for(i=0;i<nums.size();i++)
if (nums[i]==target){
a=i;
for(i=a+1;i<nums.size();i++)
if (nums[i]==target){
b=i;
}
}
else
a=-1;
b=-1;
for(i=a+1;i<nums.size();i++)
if (nums[i]==target){
b=i;
}
else b=a;
if (a == nums.size() - 1)
b=a;
return {a,b};
}
};
本文详细解析了LeetCode第34题“查找目标值的起始和终止位置”的算法思路与实现代码,该题要求在有序整数数组中找到特定目标值的开始和结束位置,若未找到则返回[-1,-1]。文章通过具体示例阐述了如何利用O(logn)的时间复杂度解决此问题。
2348

被折叠的 条评论
为什么被折叠?



