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附近。
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章