【问题标题】:Search in Rotated Sorted Array Leetcode在旋转排序数组中搜索 Leetcode
【发布时间】:2021-06-19 00:03:46
【问题描述】:

我被困在question。我的代码不断返回3 作为输入nums = [4,5,6,7,0,1,2], target = 0 的输出。我正在做一些二进制搜索的修改版本并打印中间索引的索引并检查该索引处的值是否等于目标值。二进制搜索中中间索引的值是stdout:3 5 4,而不是返回4我的程序返回3。你能告诉我我的逻辑哪里不正确吗?

class Solution {
public:
    int bin_search(vector<int>& nums,int target,int l,int r){
        int m;
        m=(r+l)/2;
        cout<<m<<" ";
        // if(r==l) break;
        if(nums[m]==target) return m;
        else if(r==l && nums[m]!=target) return -1;
        if(target>=nums[l] && target<=nums[m]){
            m=bin_search(nums,target,l,m);
        }
        else if(target>=nums[m+1] && target<=nums[r]){
            m=bin_search(nums,target,m+1,r);
        }
           
        
        // if(nums[m]==target) return m;
        return m;
    }
    
    int search(vector<int>& nums, int target) {
        int n=nums.size();
        int f;
        f=bin_search(nums,target,0,n-1);
        return f;
    }
};

【问题讨论】:

  • 二分查找只能用于已排序的数组。 (应用于数组时)
  • 当你递归调用bin_search时,你对那些调用返回的结果做了什么?
  • @Someprogrammerdude 哦,谢谢m=bin_search(nums,target,l,m) 应该在代码中。
  • 请注意,在 bin_search() 中调用 bin_search() 并将结果值丢弃是没有意义的。

标签: c++ arrays binary-search


【解决方案1】:

您必须考虑对二进制搜索方法进行一些修改,因为二进制搜索方法仅适用于排序数组。

提示:考虑查找一些子数组(已排序),然后仅对这些特定部分应用二进制搜索。

目前,您没有比较 a[low] &amp; a[mid]。只有比较这两个数组索引,您才能了解数组元素在子数组中的位置(增加或减少)。

您正在将 a[low] &amp; a[mid] 与您的 target element 进行比较,这不会输出所需的子数组关系(增加或减少)

【讨论】:

  • 我想我正在这样做你能确认吗?
  • @anfjnlnl 如果您还有其他问题,请告诉我!
  • 严格来说,不仅仅适用于 sorted 数组。看看std::binary_search()算法要求。