-
Notifications
You must be signed in to change notification settings - Fork 0
/
34.find-first-and-last-position-of-element-in-sorted-array.cpp
125 lines (124 loc) · 3.06 KB
/
34.find-first-and-last-position-of-element-in-sorted-array.cpp
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
* @lc app=leetcode id=34 lang=cpp
*
* [34] Find First and Last Position of Element in Sorted Array
*
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
*
* algorithms
* Medium (33.01%)
* Total Accepted: 270.9K
* Total Submissions: 820.3K
* Testcase Example: '[5,7,7,8,8,10]\n8'
*
* 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]
*
*/
class Solution
{
public:
vector<int> searchRange(vector<int> &nums, int target)
{
vector<int> result;
int mid = searchMid(nums, target);
if (mid == -1)
{
result.push_back(-1);
result.push_back(-1);
return result;
}
int left = searchLeft(nums, target, 0, mid);
int right = searchRight(nums, target, mid, nums.size() - 1);
cout << left << " " << right << endl;
result.push_back(left);
result.push_back(right);
return result;
}
int searchRight(vector<int> &nums, int target, int left, int right)
{
while (left + 1 < right)
{
int mid = left + (right - left) / 2;
if (target == nums[mid])
{
left = mid;
}
else
{
right = mid;
}
}
if (nums[right] == target)
return right;
if (nums[left] == target)
return left;
return -1;
}
int searchLeft(vector<int> &nums, int target, int left, int right)
{
while (left + 1 < right)
{
int mid = left + (right - left) / 2;
if (nums[mid] == target)
{
right = mid;
}
else
{
left = mid;
}
}
if (nums[left] == target)
return left;
if (nums[right] == target)
return right;
return -1;
}
int searchMid(vector<int> &nums, int target)
{
if (nums.size() == 0)
return -1;
int left = 0, right = nums.size() - 1;
while (left + 1 < right)
{
// Prevent (left + right) overflow
int mid = left + (right - left) / 2;
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] < target)
{
left = mid;
}
else
{
right = mid;
}
}
// Post-processing:
// End Condition: left + 1 == right
if (nums[left] == target)
return left;
if (nums[right] == target)
return right;
return -1;
}
};