首页 > 其他 > 详细

LeetCode Search in Rotated Sorted Array

时间:2015-02-28 23:04:07      阅读:440      评论:0      收藏:0      [点我收藏+]

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.

题意:在一个已经排好序,但是中间翻转过得数组中找目标

思路:首先对于left和right看看,A[left] <= A[right]的话那么证明这段数组是有序的,否则的话,就是一个有折点的数组,再在左右两段中继续二分

class Solution {
public:
    int search(int A[], int n, int target) {
       return find(A, 0, n-1, target); 
    }

    int find(int A[], int l, int r, int target) {
        if (l > r) return -1;

        int ans = -1;
        if (A[l] <= A[r]) {
            int left = l, right = r;
            while (left <= right) {
                int mid = left + right >> 1;
                if (A[mid] == target) {
                    ans = mid;
                    break;
                }
                if (A[mid] > target) 
                    right = mid - 1;
                else left = mid + 1;
            }
        } else {
            int mid = l + r >> 1;
            if (A[mid] == target) ans = mid;
            else {
                ans = find(A, l, mid - 1, target);
                ans = ans == -1 ? find(A, mid + 1, r, target) : ans;
            }
        }

        return ans;
    }
};



LeetCode Search in Rotated Sorted Array

原文:http://blog.csdn.net/u011345136/article/details/43991047

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!