LeetCode(33)Search in Rotated Sorted Array

本文介绍了一种在旋转过的有序数组中使用二分搜索查找特定元素的方法。通过找到旋转点并利用二分搜索提高查找效率。

题目

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.

分析

该题目是在一个旋转过的有序序列中查找关键字。
显然的,不能用一次遍历顺序查找法,考察的关键是二分搜索算法。
对于一个递增序列,在旋转点前后,也会保持递增排序不变。
所以对该题目首先要找到整个序列中的最小元素,也就是旋转点,然后对两边子序列应用二分搜索,找到目标元素的下标。

AC代码

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

        //找到旋转点
        int pivot = findPivot(nums , 0 , nums.size()-1);
        int pos = binarySearch(nums, 0, pivot - 1, target);
        if (pos != -1)
            return pos;
        else
            pos = binarySearch(nums, pivot, nums.size() - 1, target);

        return pos != -1 ? pos : -1;

    }

    //寻找旋转点
    int findPivot(vector<int> &nums , const int &lhs , const int &rhs)
    {

        if (nums.empty() || lhs > rhs)
            return -1;

        int middle = (lhs + rhs) / 2;

        //如果中间元素大于左侧首位值lhs,则旋转点要么在lhs要么在middle+1 ~ rhs
        if (nums[middle] >= nums[lhs])
        {
            int pivot = findPivot(nums, middle + 1, rhs);
            if (pivot == -1)
                return lhs;
            else if (nums[lhs] < nums[pivot])
                return lhs;
            else
                return pivot;
        }//反之,则旋转点要么在middle要么在lhs~middle-1
        else{
            int pivot = findPivot(nums, lhs, middle-1);
            if (pivot == -1)
                return middle;
            else if (nums[middle] < nums[pivot])
                return middle;
            else
                return pivot;
        }//else 
    }

    int binarySearch(vector<int> &nums, const int &lhs , const int &rhs ,int target)
    {
        if (nums.empty() || lhs > rhs)
            return -1;

        int middle = (lhs + rhs) / 2;
        if (nums[middle] == target)
            return middle;
        else if (nums[middle] < target)
        {
            return binarySearch(nums, middle + 1, rhs, target);
        }
        else{
            return binarySearch(nums, lhs, middle - 1, target);
        }//else
    }
};

GitHub测试程序源码

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值