code第一部分:数组:在反转数组中查找

code第一部分:数组:在反转数组中查找

在反转数组中查找,无重复数据
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.

分析
查找,最简单,显然从头到尾遍历一遍就可以了,但是有没有更简单的办法呢,因为没有重复的数据,
在这里我们可以使用二分查找来实现,注意边界位置的确定;注意和我们使用二分查找判定的条件有所区别;
二分查找的时间复杂度为O(logn);

源代码如下

#include <iostream>
using namespace std;

int search(int A[], int n, int target)
{
    int first = 0, last = n;
    while (first != last)
    {
        const int mid = (first + last) / 2;
        if (A[mid] == target)
            return mid;
        if (A[first] <= A[mid])
        {
            if (A[first] <= target && target < A[mid])
                last = mid;
            else
                first = mid + 1;
        }
        else
        {
            if (A[mid] < target && target <= A[last-1])
                first = mid + 1;
            else
                last = mid;
        }
    }
    return -1;
}


int search2(int A[], int n, int target)
{
    int i;
    for (i = 0; i < n; i++)
    {
        if (A[i]==target)
        {
            return i;
        }
    }
    return -1;
}

int main()
{
    int a[7]={4, 5 ,6, 7,0 ,1 ,2};
    int ans=search(a,7,2);
    cout<<ans<<endl;
    int ans1=search2(a,7,2);
    cout<<ans1<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/tao-alex/p/6442993.html