简体   繁体   中英

Leetcode #33 TIme Limit Exceeded

https://leetcode.com/problems/search-in-rotated-sorted-array/

The question requires that the solution be O(log n) and I believe that my solution is O(log n) since my process of finding the smallest element is O(log n) and then using binary search to find the target value is also O(log n). However, my code is exceeding the time limit.

int search(vector<int>& nums, int target) {
    if(nums.size() == 0){
        return -1;
    }
    int left = 0;
    int right = nums.size() - 1;
    while(left < right){
        int middle = left + (right - left) / 2;
        if(nums[left] < nums[middle]){
            left = middle;
        }
        else{
            right = middle;
        }
    }
    if(target >= nums[0]){
        return binarySearch(nums, target, 0, left - 1);
    }
    else{
        return binarySearch(nums, target, left, nums.size() - 1);
    }
}

int binarySearch(vector<int>& nums, int target, int start, int end){
    if(nums.size() == 0 || (start == end && nums[start] != target)){
        return -1;
    }
    int mid = start + (end - start) / 2;
    if(nums[mid] == target){
        return mid;
    }
    if(nums[mid] > target){
        return binarySearch(nums, target, start, mid - 1);
    }
    else{
        return binarySearch(nums, target, mid, end);
    }
}

I believe binarySearch can run into an endless loop. When end = start + 1 you will get mid = start so if nums[start] < target you end up making a recursive call with the same parameters as before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM