1.题意如下,转载力扣上面的34题,该数组本身是升序的;很多人用二分查找法,我这里简单实现
注意:当元素没有时返回【-1,-1】,当自有一个元素时,该元素下标既是第一个也是最后一个
class Solution {
public int[] searchRange(int[] nums, int target) {
int start1 = -1;
int end1 = -1;
if(nums.length == 1){
if (nums[0]==target){
//只有单个元素,既是第一个也是最后一个
start1 = 0;
end1 = 0;
}
}
else{
for(int i = 0;i<nums.length;i++){
int count = 0; //记录重复的个数
if(nums[i]==target){
count++;
if(start1 == -1 && count==1){
//只有单个元素,既是第一个也是最后一个
start1 = i;
end1 = i;
}else{
end1 = i;
}
}
}
}
int[] result = {start1,end1};
return result;
}
}