您的位置:首页 > 其它

【LeetCode】Search for a Range

2016-03-06 21:26 429 查看
Given a sorted array of integers, 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,-1]。

思路一:从左向右遍历数组,直至找到该数的范围或不存在,复杂度为o(n),很明显还有更好的方法,可以提高效率。

思路二:使用二分查找的思想

代码如下:

public int[] searchRange(int[] nums, int target) {
int[] ans = new int[2];//返回数组指针,动态分配内存

if(nums == null || nums.length == 0) {
ans[0] = -1;
ans[1] = -1;
return ans;
}
int left = 0;
int right = nums.length-1;
int mid = 0;
int flag = 0;
while(left <= right) {
mid = (left + right) / 2;
if(nums[mid] == target) {
flag = 1;
break;
} else if(nums[mid] < target){
left = mid + 1;
} else {
right = mid - 1;
}
}
if(flag == 1) {//找到了
int index1 = mid;
int index2 = mid;
while(index1-1 >= 0 && nums[index1-1] == target) {//index1-1 >= 0防止数组越界
index1--;
}
while(index2+1 < nums.length && nums[index2+1] == target) {
index2++;
}
ans[0] = index1;
ans[1] = index2;

} else {
ans[0] = -1;
ans[1] = -1;
}

return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: