【LeetCode】【HOT】34. 在排序数组中查找元素的第一个和最后一个位置
package hot;
import java.util.Arrays;
public class Solution34 {
public static void main(String[] args) {
int[] nums = {5,7,7,8,8,10};
Solution34 solution = new Solution34();
System.out.println(Arrays.toString(solution.method(nums, 8)));
}
private int[] method(int[] nums, int target){
int left = 0;
int right = nums.length - 1;
int temp = nums.length;
int leftIndex = -1;
int rightIndex = -1;
while(left <= right){
int m = (left + right) / 2;
if(nums[m] >= target){
right = m - 1;
temp = m;
}else{
left = m + 1;
}
}
leftIndex = temp;
left = 0;
right = nums.length - 1;
temp = nums.length;
while(left <= right){
int m = (left + right) / 2;
if(nums[m] > target){
right = m - 1;
temp = m;
}else{
left = m + 1;
}
}
rightIndex = temp - 1;
if(leftIndex <= rightIndex && rightIndex <= nums.length && nums[leftIndex] == target && nums[rightIndex] == target){
return new int[] {leftIndex, rightIndex};
}
return new int[] {-1, -1};
}
}