solution.md 2.3 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
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
# 在排序数组中查找元素的第一个和最后一个位置

<p>给定一个按照升序排列的整数数组 <code>nums</code>,和一个目标值 <code>target</code>。找出给定目标值在数组中的开始位置和结束位置。</p>
<p>如果数组中不存在目标值 <code>target</code>,返回 <code>[-1, -1]</code></p>
<p><strong>进阶:</strong></p>
<ul>
    <li>你可以设计并实现时间复杂度为 <code>O(log n)</code> 的算法解决此问题吗?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong>nums = [5,7,7,8,8,10], target = 8<strong><br />输出:</strong>[3,4]</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>nums = [5,7,7,8,8,10], target = 6<strong><br />输出:</strong>[-1,-1]</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>nums = [], target = 0<strong><br />输出:</strong>[-1,-1]</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
    <li><code>0 <= nums.length <= 10<sup>5</sup></code></li>
    <li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
    <li><code>nums</code> 是一个非递减数组</li>
    <li><code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code></li>
</ul>

## template

```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	vector<int> searchRange(vector<int> &nums, int target)
	{
		vector<int> res;
		res.push_back(binary_search_begin(nums, target));
		res.push_back(binary_search_end(nums, target));
		return res;
	}
private:
	int binary_search_begin(vector<int> nums, int target)
	{
		int lo = -1;
		int hi = nums.size();
		while (lo + 1 < hi)
		{
			int mid = lo + (hi - lo) / 2;
			if (target > nums[mid])
			{
				lo = mid;
			}
			else
			{
				hi = mid;
			}
		}
		if (hi == nums.size() || nums[hi] != target)
		{
			return -1;
		}
		else
		{
			return hi;
		}
	}
	int binary_search_end(vector<int> nums, int target)
	{
		int lo = -1;
		int hi = nums.size();
		while (lo + 1 < hi)
		{
			int mid = lo + (hi - lo) / 2;
			if (target < nums[mid])
			{
				hi = mid;
			}
			else
			{
				lo = mid;
			}
		}
		if (lo == -1 || nums[lo] != target)
		{
			return -1;
		}
		else
		{
			return lo;
		}
	}
};
```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```