# C#LeetCode刷题之#34-在排序数组中查找元素的第一个和最后一个位置（Find First and Last Position of Element in Sorted Array）

## 问题

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].

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

Input: nums = [5,7,7,8,8,10], target = 6

Output: [-1,-1]

## 示例

```public class Program {

public static void Main(string[] args) {
var nums = new int[] { 2, 2 };

var res = SearchRange(nums, 2);
ShowArray(res);

nums = new int[] { 5, 7, 7, 8, 8, 10 };

res = SearchRange2(nums, 8);
ShowArray(res);

}

private static void ShowArray(int[] array) {
foreach(var num in array) {
Console.Write(\$"{num} ");
}
Console.WriteLine();
}

public static int[] SearchRange(int[] nums, int target) {
//暴力线性
var res = new int[] { -1, -1 };
for(int i = 0, j = nums.Length - 1;
i <= j && (res[0] == -1 || res[1] == -1);) {
if(nums[i] == target) res[0] = i; else i++;
if(nums[j] == target) res[1] = j; else j--;
}
return res;
}

public static int[] SearchRange2(int[] nums, int target) {
//二分法
var low = 0;
var high = nums.Length - 1;
var mid = 0;
var res = new List<int>();
while(low <= high) {
mid = low + (high - low) / 2;
if(nums[mid] == target) {
var index = mid;
while(index < high) {
if(nums[++index] != target) {
index--;
break;
}
}
index = mid;
while(index > 0) {
if(nums[--index] != target) {
index++;
break;
}
}
res.Insert(0, index);
return res.ToArray();
} else if(nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return res.ToArray();
}

}```

```0 1
3 4```

## 分析

(3)

### 评论列表（2条）

• Maiza 2020年07月20日 11:43

66666