题目:
给定一个按照升序排列的整数数组 nums
,和一个目标值 target
。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]
。
示例 1:
输入: nums = [5,7,7,8,8,10]
, target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10]
, target = 6
输出: [-1,-1]
思路:根据时间复杂度可以知道使用二分法。二分法是用来在有序数组中查找元素。借鉴网上大神们的代码。
代码:
class Solution {
public int[] searchRange(int[] nums, int target) {
int i = 0, j = nums.length;
int mid = (i + j) / 2;
int p = -1;
while (i < j) { //二分法查找第一个与给定元素相同的元素,并将下标赋给p;如果找不到,则p值为-1
if (nums[mid] == target) {
p = mid;
break;
}
if (nums[mid] > target) {
if (j == mid) break; //注意边界
j = mid;
mid = (i + j) / 2;
} else {
if (i == mid) break;
i = mid;
mid = (i + j) / 2;
}
}
if (p == -1) { //找不到该元素
return new int[]{-1, -1};
} else { //以找到的第一个元素为起点,前后排查是否还有相同的元素
int a = p, b = p;
while (a > 0 && nums[a - 1] == target) a--;
while (b < nums.length - 1 && nums[b + 1] == target) b++;
return new int[]{a, b}; //创建数组的写法
}
}
}
执行最快的代码:
基本上也是二分法的思想
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
if (nums == null || nums.length == 0 || target < 0) {
result[0] = -1;
result[1] = -1;
return result;
}
result[0] = findFirst(nums, target);
result[1] = findLast(nums, target);
return result;
}
public int findFirst (int[] nums,int target) {
int index = -1;
int low = 0;
int high = nums.length - 1;
int mid;
while(low <= high) {
mid = (low + high) >> 1;
if (nums[mid] > target) {
high = mid - 1;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
index = mid;
high = mid - 1;
}
}
return index;
}
public int findLast (int[] nums,int target) {
int index = -1;
int low = 0;
int high = nums.length - 1;
int mid;
while(low <= high) {
mid = (low + high) >> 1;
if (nums[mid] > target) {
high = mid - 1;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
index = mid;
low = mid + 1;
}
}
return index;
}
}