Commit 44c67e2d authored by anqiwa's avatar anqiwa 😲
Browse files

add 34

parent 44fe2a21
/*
* @lc app=leetcode id=34 lang=cpp
*
* [34] Find First and Last Position of Element in Sorted Array
*/
// @lc code=start
class Solution
{
public:
vector<int> searchRange(vector<int> &nums, int target)
{
return {findFirst(nums, target),
findLast(nums, target)};
}
int findFirst(vector<int> &nums, int target)
{
if (nums.size() == 0)
return -1;
int l = 0, r = nums.size() - 1;
int mid;
while (l < r)
{
mid = l + (r - l) / 2;
if (nums[mid] >= target)
{
r = mid;
}
else
{
l = mid + 1;
}
}
if (nums[l] == target)
return l;
else
return -1;
}
int findLast(vector<int> &nums, int target)
{
if (nums.size() == 0)
return -1;
int l = 0, r = nums.size() - 1;
int mid;
while (l < r)
{
mid = l + (r - l) / 2 + 1;
if (nums[mid] > target)
r = mid - 1;
else
l = mid;
}
if (nums[l] == target)
return l;
else
return -1;
}
};
// @lc code=end
// r
// [5,7,7,8,8,10]
// 0 1 2 3 4 5
// l
# 34. Find First and Last Position of Element in Sorted Array
此题好像但是难写。核心无非是写两遍二分搜索,找元素的第一个和左后一个的位置,但是很难BugFree。所以这题用来锻炼二分搜索很好。我一个朋友面某faang的ng就遇到了这个题。
## 核心要点:
1. 找到第一个元素的位置
- 如果 nums[mid] >= target ,则 r = mid。 else l = mid+1;
- 这样可以使得最后的 l 所在位置是第一个元素
```cpp
while (l < r)
{
mid = l + (r - l) / 2;
if (nums[mid] >= target)
r = mid;
else
l = mid + 1;
}
```
2. 找到最后一个元素的位置
- 如果 nums[mid] <= target, 这 l = mid, else r = mid -1
- 这样可以使得最后的 l 所在位置是最后第一个元素
- 我们可以观察到一定的对称性
```cpp
while (l < r)
{
mid = l + (r - l) / 2 + 1;
if (nums[mid] <= target)
l = mid;
else
r = mid - 1;
}
```
\ No newline at end of file
class Solution
{
public:
int searchInsert(vector<int> &nums, int target)
{
int l = 0;
int r = nums.size();
while (l < r)
{
int mid = l + (r - l) / 2; // [0,1] -> 0
if (nums[mid] < target)
{
l = mid + 1;
}
else if (nums[mid] > target)
{
r = mid;
}
else
{
return mid;
}
}
return r;
}
};
\ No newline at end of file
......@@ -6,14 +6,15 @@
<br/><br/>
### <b/>分类目录</b>
[Binary Search]()
[Binary Search](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Binary%20Search)
[35. Search Insert Position]()
[35. Search Insert Position](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Binary%20Search/35.%20Search%20Insert%20Position) (E-)
[34. Find First and Last Position of Element in Sorted Array]()
[1060. Missing Element in Sorted Array]()
<br/> </br>
[Linked List](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Linked%20List)
[328.odd even linked list](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Linked%20List/328%20odd%20even%20Linked%20List) (M-)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment