简体   繁体   English

在旋转排序数组中搜索 Leetcode

[英]Search in Rotated Sorted Array Leetcode

I'm stuck in the question .我陷入了这个 问题 My code keeps returning 3 as output for the input nums = [4,5,6,7,0,1,2], target = 0 .对于输入nums = [4,5,6,7,0,1,2], target = 0我的代码一直返回3作为 output。 I'm doing some modified version of binary search and printing the indices of middle index and checking whether value at that index is equal to the target value.Values of middle indices in binary search are stdout:3 5 4 but instead of returning 4 my program returns 3 .我正在做二进制搜索的一些修改版本并打印中间索引的索引并检查该索引处的值是否等于目标值。二进制搜索中中间索引的值是stdout:3 5 4但不是返回4 my程序返回3 Can you please tell me where my logic is incorrect?你能告诉我我的逻辑哪里不正确吗?

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

You'll have to think on some modification in the binary search approach because binary search approach is applicable only for sorted array.您必须考虑对二进制搜索方法进行一些修改,因为二进制搜索方法仅适用于排序数组。

Hint : Think about finding some subarrays (which are sorted) and then apply binary search only on those specific parts.提示:考虑找到一些子数组(已排序),然后仅对这些特定部分应用二进制搜索。

Currently, you are not comparing a[low] & a[mid] .目前,您没有比较a[low] & a[mid] Only if you compare these two array indices, you'll get an idea of how the array elements are in the subarray (increasing or decreasing).只有比较这两个数组索引,您才能了解数组元素在子数组中的情况(增加或减少)。

You are comparing a[low] & a[mid] with your target element , which will not output the desired relation of subarray(increasing or decreasing)您正在将a[low] & a[mid]target element进行比较,这不会 output 所需的子数组关系(增加或减少)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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