1.给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
类似的题目
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
题解:
int binary_find(int *nums, int numsSize, int target) {
int low = 0;
int high = numsSize - 1;
int mid = 0;
int midVal = 0;
while (low <= high) {
mid = (low + high) / 2;
midVal = nums[mid];
if (midVal < target) {
low = mid + 1;
} else if (midVal > target) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
在排序数组中查找元素的第一个和最后一个位置
*/
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
int find = binary_find(nums, numsSize, target);
int i = 0;
int *array = (int *)calloc(2, sizeof(int));
*returnSize = 2;
if (-1 == find) {
array[0] = -1;
array[1] = -1;
} else {
array[0] = find;
array[1] = find;
i = find + 1;
while (i < numsSize) {
if (nums[i] == target)
{
array[1] = i;
} else {
break;
}
i++;
}
i = find -1;
while (i >= 0) {
if (nums[i] == target) {
array[0] = i;
} else {
break;
}
i--;
}
}
return array;
}
/* 数字在排序数组中出现的次数 */
int search(int* nums, int numsSize, int target){
int find = binary_find(nums, numsSize, target);
int i = 0;
int count = 0;
if(-1 == find) {
return 0;
}
count++;
i = find + 1;
while(i < numsSize) {
if(nums[i] == target) {
count++;
} else {
break;
}
i++;
}
i = find - 1;
while(i >= 0) {
if(nums[i] == target) {
count++;
} else {
break;
}
i--;
}
return count;
}