链接:
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
大意:
给定一个有序数组(升序,有重复数字)nums以及一个待查找的数字target,返回target在数组nums中出现的首位置和尾位置组成的数组,如果target在nums中不存在,则返回[-1,-1]。要求时间复杂度为O(logn)。例子:
思路:
先通过二分查找法找到target在nums中的一个位置(若不存在则返回数组[-1,-1]),记为index。之后从index往左找target在nums中出现的首位置,从index往右找target在nums中出现的尾位置。
代码:
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0 || nums.length == 1 && nums[0] != target)
return new int[]{-1, -1};
int[] res = new int[]{-1, -1};
int s = 0, e = nums.length - 1, index = -1;
// 二分法查找
while (s <= e) {
int mid = (s + e) / 2;
if (target > nums[mid])
s = mid + 1;
else if (target < nums[mid])
e = mid - 1;
else {
index = mid;
break;
}
}
if (index == -1)
return res;
res[0] = res[1] = index;
while (res[0] - 1 >= 0 && nums[res[0] - 1] == target) {
res[0]--;
}
while (res[1] + 1 <= nums.length - 1 && nums[res[1] + 1] == target) {
res[1]++;
}
return res;
}
}
结果:
结论:
找到target在nums中的一个位置index时,往左找需要先判断 index - 1位置的值是否为target,如果是target,再将index-1;如果不是target,则跳出循环。往右找也是如此