码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(33)Search in Rotated Sorted Array

时间:2015-08-25 19:43:47      阅读:156      评论:0      收藏:0      [点我收藏+]

标签: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.

分析

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

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测试程序源码

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode(33)Search in Rotated Sorted Array

标签:leetcode   搜索   

原文地址:http://blog.csdn.net/fly_yr/article/details/47980245

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!