简介
暴力, 不过推荐官方的二分查找
code
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
bool check = false;
int indexS=-1, indexE = -1;
for(int i=0; i<nums.size(); i++){
if(nums[i] == target && !check){
indexS = i;
check = true;
}else if(check && nums[i] > target){
indexE = i - 1;
check = false;
return {indexS, indexE};
}
if(nums[i] > target && !check) return {-1, -1};
}
if(check && indexE == -1) {
indexE = nums.size() - 1;
}
return {indexS, indexE};
}
};
class Solution {
public int[] searchRange(int[] nums, int target) {
int len = nums.length;
if(len == 0) {
return new int[]{-1, -1};
}
int firstPosition = findFirstPosition(nums, target);
if(firstPosition == -1){
return new int[] {-1, -1};
}
int lastPosition = findLastPosition(nums, target);
return new int[]{firstPosition, lastPosition};
}
private int findLastPosition(int[] nums, int target) {
int left = 0;
int right = nums.length -1;
while(left < right) {
int mid = (left + right + 1) >>> 1; // 让其更靠近右边界
if(nums[mid] < target) {
left = mid + 1;
} else if(nums[mid] == target) {
left = mid;
} else{
right = mid - 1;
}
}
return left;
}
private int findFirstPosition(int[] nums, int target) {
int left = 0;
int right = nums.length -1;
while(left < right) {
int mid = (left + right) >>> 1;
if(nums[mid] < target) {
left = mid + 1;
} else if(nums[mid] == target) {
right = mid;
} else{
right = mid - 1;
}
}
if(nums[left] == target){
return left;
}
return -1;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》