来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。
给定一个按照升序排列的整数数组 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]
执行用时: 8 ms
内存消耗: 7.4 MB
时间复杂度:O(log n)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int binarySearch(int* nums, int numsSize, int target, bool lower) {
int left = 0, right = numsSize - 1, ans = numsSize;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target || (lower && nums[mid] >= target)) {
right = mid - 1;
ans = mid;
} else {
left = mid + 1;
}
}
return ans;
}
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
int* ret = malloc(sizeof(int) * 2);
ret[0] = -1, ret[1] = -1;
*returnSize = 2;
int leftIdx = binarySearch(nums, numsSize, target, true);
int rightIdx = binarySearch(nums, numsSize, target, false) - 1;
if (leftIdx <= rightIdx && rightIdx < numsSize && nums[leftIdx] == target && nums[rightIdx] == target) {
ret[0] = leftIdx, ret[1] = rightIdx;
}
return ret;
}
第二种方式:
执行用时: 20 ms
内存消耗: 7.5 MB
时间复杂度:最坏=O(n) 最好= O(log n)
什么时候会是O(n) ? 比如说targent = m,有 n 个 m的数组
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
int *res = (int *)calloc(sizeof(int), 2);
res[0] = res[1] = -1;
* returnSize = 2;
int l = 0, r = numsSize, mid;
while (l < r) {
mid = (l+r) >> 1;
if (nums[mid] > target) {
r = mid;
} else if (nums[mid] < target) {
l = mid+1;
} else {
res[0] = res[1] = mid;
break;
}
}
if (res[0] != -1) {
while ( res[0]-1 >= 0 && nums[res[0]] == nums[res[0]-1] ) {
res[0]--;
}
while ( res[1]+1 < numsSize && nums[res[1]] == nums[res[1]+1] ) {
res[1]++;
}
}
return res;
}