34. 在排序数组中查找元素的第一个和最后一个位置(两种方法记录)
法一(BP算法——使用双指针分别从前、后定位first index和last index),代码如下:
class Solution {
public int[] searchRange(int[] nums, int target) {
// the first method
int[] index = new int[]{
-1,-1};
if(nums.length==0)return new int[]{
-1,-1};
else{
int slow,fast;
for(slow=0;slow<nums.length;slow++){
if(nums[slow]==target){
index[0] = slow; // find the first index
for(fast=nums.length-1;fast>=slow;fast--){
if(nums[fast]==target){
index[1] = fast; // find the second index
break;
}//else if(nums[fast]<){} impossible
}
break; // important
}else if