【问题标题】:Leetcode #33 TIme Limit ExceededLeetcode #33 超过时间限制
【发布时间】:2020-05-27 03:10:13
【问题描述】:

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

问题要求解决方案是 O(log n),我相信我的解决方案是 O(log n),因为我找到最小元素的过程是 O(log n),然后使用二进制搜索找到目标值也是 O(log n)。但是,我的代码超过了时间限制。

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);
    }
}

【问题讨论】:

  • 当你在你的电脑上用测试输入运行它会发生什么?
  • 它在我的编译器上运行良好并给出了正确的输出,但它超过了 leetcode 的时间限制
  • leetcode 是否让你知道是哪个输入导致了超时问题?
  • std::binary_searchstd::upper_bound / std::lower_bound替换所有代码。

标签: c++ arrays sorting


【解决方案1】:

我相信 binarySearch 会陷入死循环。当 end = start + 1 你将得到 mid = start 所以如果 nums[start]

【讨论】:

  • 在迭代二分搜索中也会发生同样的事情。递归二分搜索的解决方案是执行int mid = start + (end - start + 1) / 2(或int mid = start + (end - start) / 2 + ((end - start) &amp; 1),如果您对溢出有偏执)这将使除法向上。
猜你喜欢
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 2022-07-16
  • 1970-01-01
  • 2022-08-24
相关资源
最近更新 更多