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

Search in Rotated Sorted Array -- leetcode

时间:2015-01-11 09:45:00      阅读:219      评论:0      收藏:0      [点我收藏+]

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


版本一,递归实现

在leetcode上,实际执行时间为7ms。

算法基本思路依据为,将区间折半后,必有一半是递增的(左端点的值小于右端点的值)。

看要找的值在此区间中没,若在,在此区间继续搜索。否则,进入另一半区间。

class Solution {
public:
    int search(int A[], int n, int target) {
        if (!n) return -1;

        bool first = false;
        const int mid = (n-1) / 2;
        if (A[mid] == target)
                return mid;
        else if ((A[0] <= target && target < A[mid]))
                first = true;
        else if (A[mid] < target && target <= A[n-1])
                first = false;
        else if (A[0] > A[mid])
                first = true;

        if (first)
                return search(A, mid, target);
        else {
                const int result = search(A+mid+1, n-mid-1, target);
                return result != -1 ? result + mid+1 : -1;
        }
    }
};


版本2:非递归实现

其思路与上同。 只是将上面的代码加入了while循环。

执行时间也是7ms。

class Solution {
public:
    int search(int A[], int n, int target) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
                bool first = false;
                const int mid = low + (high - low) / 2;
                if (A[mid] == target)
                        return mid;
                else if ((A[0] <= target && target < A[mid]))
                        first = true;
                else if (A[mid] < target && target <= A[n-1])
                        first = false;
                else if (A[0] > A[mid])
                        first = true;

                if (first)
                        high = mid - 1;
                else
                        low = mid + 1;
        }

        return -1;
    }
};



Search in Rotated Sorted Array -- leetcode

标签:leetcode   search   rotated   sorted   array   

原文地址:http://blog.csdn.net/elton_xiao/article/details/42586373

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