Leetcode: 34. Search for range(Week9, Medium)

注:本题采用二分法的思想

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

  • 题意:设计一个算法找到target的index范围,并且该算法的时间复杂度是O(log n)
  • 思路:正常情况下,使用遍历的代码非常简洁,可以很轻易的解决这个问题。然而题目有时间复杂度的限制,O(log n)让我立刻反应出使用二分法的思想。
  • 算法
    • 先使用二分法,找到数组中其中一个target的index;
    • 然后使用两个while循环,以二分法得到的index为起点向两边扩展;
    • 当达到边界时,记录下边界的位置,得到index的范围。

代码如下:

/* 2017/11/5 34. Search for range 思路: 1.先用二分法找到目标值index; 2.然后以这个index为起点,向两边扩展,得到目标index的范围 */
class Solution {
public:
    int search_target(vector<int>& nums, int target) {
        if (nums.size() == 0) return -1;
        int top = nums.size()-1;
        int mid = (nums.size()-1)/2;
        int low = 0;
        while(1) {
            if (low >= top) {
                if (nums[low] != target) {
                    return -1;
                } else {
                    return low;
                }
            }
            if (nums[mid] < target) {
                low = mid+1;
            } else if (nums[mid] > target) {
                top = mid-1;
            } else {
                return mid;
            }
            mid = low + (top-low)/2;
        }
    }
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> result(2, 0);
        result[0] = search_target(nums, target);
        result[1] = result[0];
        if (result[0] == -1) return result;
        while(result[0] >= 0) {
            if (nums[result[0]] == target) {
                if (result[0] == 0) break;
                result[0]--;
            } else {
                result[0]++;
                break;
            }
        }
        while(1) {
            if (nums[result[1]] == target) {
                if (result[1] == nums.size()-1) break;
                result[1]++;
            } else {
                result[1]--;
                break;
            }
        }
        return result;
    }
};

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!

点赞