[leetcode]Search in Rotated Sorted Array

时间:2014-11-23 16:04:30   收藏:0   阅读:133

问题描述:

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.


基本思想:

此题很简单,最笨的方法就是一个一个找,如果好一点,可以设定一些条件进行剪枝。


代码:

int search(int A[], int n, int target) {  //C++
        if(n < 0)
            return -1;
        if(n == 1)
            if(A[0] == target)
                return 0;
            else return -1;
        
        if(A[0] == target)
            return 0;
        for(int i = 1; i < n; i++)
        {
            if(A[i] < A[i-1])
            {
                if(A[i] > target || A[i-1] < target || target > A[n-1])
                return -1;
            }
            if(A[i] == target )
                return i;
        }
        return -1;
    }


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!