# Leetcode算法Java全解答–34. 在排序数组中查找元素的第一个和最后一个位置

## 题目

示例 1:



## 代码

### 我的答案

   public int[] searchRange(int[] nums, int target) {
if(nums.length==0){
return new int[]{-1,-1};
}

int left = 0;
int right = nums.length;
int mid = (left+right)/2;
int targetIndex = -1;

while(left<right){
if(nums[mid]>target){
if(right == mid) break;
right = mid;
mid = (left + right) /2 ;
}else if(nums[mid]<target){
if(left == mid) break;
left = mid;
mid = (left + right) /2 ;
}else{
targetIndex = mid;
break;
}
}
if (targetIndex == -1) {
return new int[]{-1, -1};
} else {
int a = targetIndex, b = targetIndex;
while (a > 0 && nums[a - 1] == target) a--;
while (b < nums.length - 1 && nums[b + 1] == target) b++;
return new int[]{a, b};
}
}


### 大佬们的答案

 public int[] searchRange(int[] nums, int target) {
int[] result = new int[] { -1, -1 };
if (null == nums || nums.length == 0) {
return result;
}
int pos = findPos(nums, target, 0, nums.length);
if (pos == -1) {
return result;
}
result[0] = testPosL(nums, target, 0, pos);
result[1] = testPosR(nums, target, pos, nums.length - 1);
return result;
}

public int findPos(int[] nums, int target, int start, int end) {
int pos = start + (end - start) / 2;
if (null == nums || nums.length == 0 || start >= end) {
return -1;
}
int m = nums[pos];
if (m == target) {
return pos;
}
if (m > target) {
return findPos(nums, target, start, pos);
} else {
return findPos(nums, target, pos + 1, end);
}

}

private int testPosL(int[] nums, int target, int l, int r) {
int m;
while (l < r) {
m = (l + r) / 2;
if (nums[m] < target) {
l = m + 1;
} else {
r = m;
}
}
if (l < 0 || l > nums.length - 1 || nums[l] != target)
return -1;
return l;
}

private int testPosR(int[] nums, int target, int l, int r) {
int m;
while (l <= r) {
m = (l + r) / 2;
if (nums[m] > target) {
r = m - 1;
} else {
l = m + 1;
}
}
if (r < 0 || r > nums.length - 1 || nums[r] != target)
return -1;
return r;
}


### 测试用例




## 其他

“大佬们的答案” 标签来自leetcode，侵权请联系我进行删改

07-26 89
05-16 1380
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客