题目描述
题目难度:Medium
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
- Input: nums = [5,7,7,8,8,10], target = 8
- Output: [3,4]
Example 2:
-
Input: nums = [5,7,7,8,8,10], target = 6
-
Output: [-1,-1]
AC代码1
这个题感觉没什么亮点,不做也罢
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[]{-1,-1};
if(nums == null || nums.length == 0) return res;
for(int i = 0;i < nums.length;i++)
if(nums[i] == target) {
res[0] = i;
break;
}
for(int i = nums.length - 1;i >= 0;i--)
if(nums[i] == target) {
res[1] = i;
break;
}
return res;
}
}
AC代码2
class Solution {
public int[] searchRange(int[] nums, int target) {
int lo=0;
int hi = nums.length;
int[] targetRange = {-1, -1};
boolean found = false;
int mid = -1;
while(lo<hi){
mid = (lo+hi)/2;
if(target == nums[mid]){
found = true;
break;
}
if(nums[mid]>target){
hi = mid;
} else {
lo = mid+1;
}
}
if(found){
int left = mid;
while(mid>=0 && mid < nums.length && nums[mid]==target){
mid--;
}
targetRange[0]=mid+1;
mid=left;
while(mid>=0 && mid < nums.length && nums[mid]==target){
mid++;
}
targetRange[1]=mid-1;
}
return targetRange;
}
}