题:https://leetcode.com/problems/search-for-a-range/description/
题目
Given an array of integers 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].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
思路
原创
1.时间复杂度为O(log n) 说明必须使用,二分查找等方法。
2.通过二分查找找到target在数组中的位置,若未找到直接返回{-1 ,-1}
3.确定target的index后,分别向左向右遍历,查找target的左右边界。
code
import java.util.Vector;
class Solution {
public int[] searchRange(int[] nums, int target) {
int lo=0,hi = nums.length-1;
int mid = 0;
boolean flag = true;
while(lo<=hi){
mid = (lo+hi)/2;
if(nums[mid]==target){
flag = false;
break;
}
else if(nums[mid]>target) hi = mid-1;
else lo = mid + 1;
}
if(flag){
int []arrayresult = {-1,-1};
return arrayresult;
};
int leftindex = mid - 1;
while (leftindex >= 0 && nums[leftindex] == target){
leftindex = leftindex - 1;
}
leftindex += 1;
int rightindex = mid + 1;
while(rightindex <= nums.length - 1 && nums[rightindex] == target){
rightindex = rightindex + 1;
}
rightindex -= 1;
int []arrayresult = new int[2];
arrayresult[0] = leftindex;
arrayresult[1] = rightindex;
return arrayresult;
}
}
转载 leedcode 中的答案
1.通过二分查找target的边界。参考注释
class Solution {
public int[] searchRange(int[] nums, int target) {
int []arrayresult = {-1,-1};
// Search for the left one
int lo=0,hi = nums.length-1;
while(lo<hi){
int mid = (lo+hi)/2;
if(nums[mid]<target) lo = mid + 1;
else hi = mid;
}
if(nums.length==0 || nums[lo]!= target) return arrayresult;
arrayresult[0] = lo;
// Search for the right one
lo = 0;
hi = nums.length-1;
while(lo<hi){
int mid = (lo+hi+1)/2; // Make mid biased to the right
if(nums[mid]>target) hi = mid -1;
else lo = mid; // So that this won't make the search range stuck.
}
arrayresult[1] = hi;
return arrayresult;
}
}