# 在排序數組Leetcode解決方案中查找元素的第一個和最後一個位置

## 例

`array: [1,2,5,5,5,9] , target=5`
`[2,4]`

## 途徑

1. 找到目標元素後，程序不會立即終止。 我們將運行循環直到start = end。
2. 另一個更改是在arr [mid] == target的時候。
1. 對於第一次出現，end = mid-1。
2. 對於最後一次出現，start = mid + 1。

## 代碼在排序數組Leetcode解決方案中查找元素的第一個和最後一個位置

### C ++代碼

```#include <bits/stdc++.h>
using namespace std;
int findFirst(vector<int>& nums, int target)
{
int ans = -1;
int s = 0;
int e = nums.size() - 1;
while(s <= e){
int mid =s+ (e-s) / 2;
if (nums[mid] < target)
s = mid + 1;
else if (nums[mid] > target)
e = mid - 1;
else  {
ans = mid;
e = mid - 1;
}
}
return ans;
}
int findLast(vector<int>& nums, int target)
{
int ans = -1;
int s = 0;
int e = nums.size() - 1;
while(s <= e){
int mid =s+ (e-s) / 2;
if (nums[mid] < target)
s = mid + 1;
else if (nums[mid] > target)
e = mid - 1;
else  {
ans = mid;
s = mid + 1;
}
}
return ans;
}
vector<int> find(vector<int>& nums, int target) {
vector<int>result(2);
result[0] = findFirst(nums, target);
result[1] = findLast(nums, target);
return result;
}

int main()
{
vector<int> arr = {1,2,5,5,5,9};
int target=5;
vector<int> ans(2);
ans=  find(arr,target);
for(int i=0;i<2;i++)
cout<<ans[i]<<" ";
return 0;
}```
`[2,4]`

### Java代碼

```import java.util.Arrays;
public class Tutorialcup {
public static int[] find(int[] nums, int target) {
int[] result = new int[2];
result[0] = findFirst(nums, target);
result[1] = findLast(nums, target);
return result;
}

private static int findFirst(int[] nums, int target){
int ans = -1;
int s = 0;
int e = nums.length - 1;
while(s <= e){
int mid =s+ (e-s) / 2;
if (nums[mid] < target)
s = mid + 1;
else if (nums[mid] > target)
e = mid - 1;
else  {
ans = mid;
e = mid - 1;
}
}
return ans;
}

private static int findLast(int[] nums, int target){
int ans = -1;
int s = 0;
int e = nums.length - 1;
while(s <= e){
int mid =s+ (e-s) / 2;
if (nums[mid] < target)
s = mid + 1;
else if (nums[mid] > target)
e = mid - 1;
else  {
ans = mid;
s = mid + 1;
}
}
return ans;
}
public static void main(String[] args) {
int [] arr = {1,2,5,5,5,9};
int target=5;
int[] ans = new int[2];
ans=  find(arr,target);
System.out.println(Arrays.toString(ans));
}
}```
`[2,4]`