原题网址:https://leetcode.com/problems/search-for-a-range/
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].
方法:二分法查找。
public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] range = new int[2];
range[0] = -1;
range[1] = -1;
int i=0, j=nums.length-1;
while (i<=j) {
int m = (i+j)/2;
if (target == nums[m]) {
range[0] = m;
j = m-1;
} else if (target < nums[m]) {
j = m - 1;
} else {
i = m + 1;
}
}
i=0;
j=nums.length-1;
while (i<=j) {
int m = (i+j)/2;
if (target == nums[m]) {
range[1] = m;
i = m + 1;
} else if (target < nums[m]) {
j = m - 1;
} else {
i = m + 1;
}
}
return range;
}
}

本文介绍了一种使用二分法查找算法解决在已排序整数数组中寻找特定目标值起始和结束位置的问题。该算法的时间复杂度为O(log n),符合题目要求。通过两次遍历分别确定目标值的开始和结束位置。
446

被折叠的 条评论
为什么被折叠?



