LintCode : 搜索旋转排序数组

LintCode : 搜索旋转排序数组

假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。

你可以假设数组中不存在重复的元素。

方案一:遍历所有元素

没有什么技术含量,就是遍历数组的所有元素, 时间复杂度O(n)。


class Solution {
    /** * param A : an integer ratated sorted array * param target : an integer to be searched * return : an integer */
public:
    int search(vector<int> &A, int target) {
        // write your code here
        if (A.size() == 0) return -1;
        for (int i=0; i<A.size(); i++){
            if (A[i] == target) return i;
        }
        return -1;
    }
};

方案二:二分法

你可能感兴趣的:(搜索,lintcode)