Commit 65a15124 authored by anqiwa's avatar anqiwa 😲
Browse files

added 35 code

parent 85c66a1e
# 34. Find First and Last Position of Element in Sorted Array
此题好但是难写。核心无非是写两遍二分搜索,找元素的第一个和左后一个的位置,但是很难BugFree。所以这题用来锻炼二分搜索很好。我一个朋友面某faang的ng就遇到了这个题。
此题好但是难写。核心无非是写两遍二分搜索,找元素的第一个和左后一个的位置,但是很难BugFree。所以这题用来锻炼二分搜索很好。我一个朋友面某faang的ng就遇到了这个题。
## 核心要点:
......
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
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