33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

题意:略。一个升序数组在某点旋转后会出现的情况

0 1 2 4 5 6 7
4 5 6 7 0 1 2
7 0 1 2 4 5 6
1 2 4 5 6 7 0

最直接的办法分情况考虑(好蠢好蠢的)
1.恰好等于nums[mid]
2.比nums[mid]小,出现左右两边都有可能,如果target比nums[l]大肯定在左边了就–r;else比target右边还小就在右边了,然后是和nums[l],nums[r]分别相等,直接返回,否则就返回-1
3.同上考虑

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = 0, r = nums.size() - 1;
        int mid;
        while(l <= r){
            mid = l + (r - l) / 2;
            if(nums[mid] == target)
                return mid;
            else if(target < nums[mid]){
                if(target == nums[l])
                    return l;
                else if(target == nums[r])
                    return r;
                else if(target > nums[l])
                    r = mid - 1;
                else if(target < nums[r])
                    ++l;
                else 
                    return -1;
            } else if(target > nums[mid]){
                if(target == nums[l])
                    return l;
                else if(target == nums[r])
                    return r;
                else if(target > nums[l])
                    --r;
                else if(target < nums[r])
                    l = mid + 1;
                else 
                    return -1;
            }
        }
        return -1;
    }
};

根据题意可以得出,Array可以分为两种情况:右边递增或者左边递增。在每种情况下判断target的情况

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int len = nums.size();
        int l, r, m;
        l = 0, r = len - 1;
        while(l <= r){
            m = (r + l) / 2;
            if(target == nums[m])
                return m;
            else if(nums[r] >= nums[m]){
                if(nums[m] < target && target < nums[r])   
                    l = m + 1;
                else if(nums[r] == target)
                    return r;
                else
                    r = m - 1;
            } else if(nums[l] <= nums[m]){
                if(nums[l] < target && target < nums[m])
                    r = m - 1;
                else if(nums[l] == target) 
                    return l;
                else
                    l = m + 1;
            }                
        }
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值