034 - Search for a Range

来源:互联网 发布:手机简单制图软件 编辑:程序博客网 时间:2024/05/19 01:59

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].



给定一个排好序的数列,用logn的时间查找一个给定的数的下标区间,如果顺序遍历,时间复杂度为O(n),所以得用二分法找

int find(int* nums, int numsSize, int target, int lr){int left = 0, right = numsSize - 1, mid;while (left <= right) {mid = (left + right) / 2;if (nums[mid] < target) left = mid + 1;else if (nums[mid] > target) right = mid - 1;else {if (lr == 0) right = mid - 1;else left = mid + 1;}}if (lr == 0 && nums[left] == target) return left;if (lr == 1 && nums[right] == target) return right;return -1;}int* searchRange(int* nums, int numsSize, int target, int* returnSize) {int *ret = (int *)malloc(sizeof(int) * 2);*returnSize = 2;int left = find(nums, numsSize, target, 0);if (left < 0) {ret[0] = ret[1] = -1;return ret;}int right = find(nums, numsSize, target, 1);if (right < 0) {ret[0] = ret[1] = -1;return ret;}ret[0] = left;ret[1] = right;return ret;}


0 0