leetcode:在旋转排序数组中搜索

时间:2019-05-29 02:17:42

标签: javascript algorithm sorting

我正在看这个question

一种解决方案类似于this

class Solution:
    def search(self, nums: 'List[int]', target: int) -> int:
        L, H = 0, len(nums)
        while L < H:
            M = (L+H) // 2
            if target < nums[0] < nums[M]: # -inf
                L = M+1
            elif target >= nums[0] > nums[M]: # +inf
                H = M
            elif nums[M] < target:
                L = M+1
            elif nums[M] > target:
                H = M
            else:
                return M
        return -1

代替使用nums[0]

我尝试使用nums [last]

这是代码,尝试了多次,无法使其正常工作。

var search = function(n, tar) {
    let lo = 0;
    let hi = n.length;
    let m;
    let last = n.length-1;
    const max = Number.MAX_SAFE_INTEGER;
    const min = Number.MIN_SAFE_INTEGER;

    while(lo < hi) {
        // this is index
        m = Math.floor( (lo+hi)/2 ); 

        if(tar == n[m]) {
            return m;  
        } else if(tar == n[last]) {
            return last;
        } else if(tar < n[last] && n[m] > n[last]) {
            // n[m]...........tar.....n[last]
            lo = m+1;
        } else if(tar > n[last] && n[m] < n[last]) {
            // tar........n[m]......n[last]
            hi = m;
        } else if(tar < n[last] && tar < n[m]) {
            // ...........tar, n[m], n[last]
            hi = m;
        } else if(tar < n[last] && tar < n[m]) {
            // ............n[m], tar, n[last]
            lo= m+1;
        } else if(tar > n[last] && tar < n[m]) {
            // tar, n[m].......... n[last]
            hi=m;
        } else if(tar > n[last] && tar > n[m]) {
            // n[m], tar.......... n[last]
            lo=m+1;
        } else {
            return m;
        } 
    }

    return -1;
};

1 个答案:

答案 0 :(得分:-1)

这是我的解决方案,它可以工作。希望对您有所帮助:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        return recSearch(nums, target, 0, nums.size()-1);

    }

    int recSearch (vector<int>& nums, int target, int s, int t){
        int m = (s+t)/2;
        if (nums[m] == target) { return m;}
        if (s==t) {return -1;}
        if (nums[s] < nums[m]){
            if (nums[s] <= target && nums[m] > target){ 
                return recSearch(nums, target, s, m-1);
            }
            return recSearch(nums, target, m+1, t);
        }
        if (nums[m] < target && nums[t] >= target){ 
            return recSearch(nums, target, m+1, t);
        }
        return recSearch(nums, target, s, m-1);

    }
};