leetcode题目 旋转排序数列的查找

题目: Suppose a sorted array 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.
思路: 普通的二分查找只有两种情况,而旋转数列的查找则有6种情况,分情况移动前后指针即可。当然,递归也可以实现。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int fir=0;
        int sec=nums.size()-1;
        int mid=0;
        bool Isfront=false;
        if(target>=nums[0])
            Isfront=true;
        while(fir>=0&&sec>=0&&fir<nums.size()&&sec<nums.size()&&fir<=sec)
        {
            mid=(fir+sec)/2;
            if(nums[mid]>=nums[0])
            {
                if(nums[mid]<target)
                {
                    fir=mid+1;
                    continue;
                }
                else if(nums[mid]>target)
                {
                    if (Isfront)
                    {
                        sec = mid - 1;
                        continue;
                    }
                    else
                    {
                        fir = mid + 1;
                        continue;
                    }
                }
                else
                    return mid;
            }
            else
            {
                if(nums[mid]<target)
                {
                    if(Isfront)
                    {
                        sec=mid-1;
                        continue;
                    }
                    else
                    {
                        fir=mid+1;
                        continue;
                    }

                }
                else if(nums[mid]>target)
                {
                    sec=mid-1;
                    continue;
                }
                else
                    return mid;
            }
        }
        return -1;
    }
};

运行时间4ms,测试结果虽然只击败了12%的代码,但是看到大家都集中在4ms附近。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值