Skip to content

LeetCode: 34. 搜索范围 #79

Open

Description

@resse92

思路:
二分查找法,找到target的某个位置,向两边扩散找到边界即可。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int targetIndex = findTarget(nums, target);
        if (targetIndex == -1) {
            return {-1, -1};
        }
        int first = targetIndex;
        while (first >= 0) {
            if (nums[first] == target) {
                first -= 1;
            } else {
                break;
            }
        }
        int last = targetIndex;
        while (last < nums.size()) {
            if (nums[last] == target) {
                last += 1;
            } else {
                break;
            }
        }
        return {first + 1, last - 1};
    }
    
    int findTarget(vector<int>& nums, int target) {
        int first = 0, last = nums.size();

        while (first != last) {
            const int mid = (first + last) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            
            if (nums[first] <= nums[mid]) {
                if (nums[first] <= target && target < nums[mid]) {
                    last = mid;
                } else {
                    first = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[last - 1]) {
                    first = mid + 1;
                } else {
                    last = mid;
                }
            }
        }
        
        return -1;
    }
};

Activity

  1. changed the title [-]e[/-] [+]LeetCode: 34. 搜索范围[/+] on Jun 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions