34. Find First and Last Position of Element in Sorted Array

每日一题 2019 - 03 - 25

题目:

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:

1
2
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

1
2
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

解法:

这个题让我们找出在一个排序好的数组中的某一个元素的起始位置与结束位置且要求时间复杂度为o(logn),那么很直接的思路就是使用二分查找的方式:

  • 需要讲一点的就是,如果我们找到一个元素且这个元素有很多个重复出现,那么可以从这个元素往前推找到起始位置,从这个元素往后推找到终止位置,最后把这两个位置放到 vector

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left = 0 , right = nums.size() - 1 ;
if(nums.size() == 1)
{
vector<int> temp ;
if(nums[0] == target)
{
temp.push_back(0);
temp.push_back(0);
}
else
{
temp.push_back(-1);
temp.push_back(-1);
}
return temp ;
}
while(left <= right)
{
int mid = (left + right) / 2 ;
if(nums[mid] == target)
{
vector<int> now;
int before = mid ;
int end = mid ;
while(before >= 0)
{
if(nums[before] == target)
{
before -- ;
}
else
{
break ;
}
}
now.push_back(before+1);
while(end <= nums.size() - 1)
{
if(nums[end] == target)
{
end ++ ;
}
else
{
break ;
}
}
now.push_back(end -1);
return now ;
}
else if(nums[mid] < target)
{
left = mid + 1 ;
}
else
{
right = mid - 1 ;
}
}
vector<int> temp ;
temp.push_back(-1);
temp.push_back(-1);
return temp ;
}
};
0%
undefined