34. Search for a Range

xiaoxiao2021-02-28  14

Given an array of integers sorted in ascending order, 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].

这一题的意思是给定一个以升序排好序的序列和一个目标值,然后找出该目标值的第一次出现的位置和最后一次出现的位置。题目比较简单,因为已经排好序了,所以一个O(logn)的做法就是用二分查找。所以二分查找也是比较基础的一个算法,不详细讲,代码如下:

Code(LeetCode运行9ms)

class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> result(2); result[0] = result[1] = -1; if (nums.size() == 0) { return result; } int pos = findTarget(nums, 0, nums.size() - 1, target); result[0] = result[1] = pos; for (int i = pos + 1; i < nums.size(); i++) { if (nums[i] != target) { result[1] = i - 1; break; } else { result[1]++; } } for (int i = pos - 1; i >= 0; i--) { if (nums[i] != target) { result[0] = i + 1; break; } else { result[0]--; } } return result; } int findTarget(vector<int> nums, int start, int end, int target) { if (start > end) { return -1; } int mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { return findTarget(nums, mid + 1, end, target); } else { return findTarget(nums, start, mid - 1, target); } } };

转载请注明原文地址: https://www.6miu.com/read-1400400.html

最新回复(0)