剑指offer--面试题8

题目:求旋转数组中的最小数字

以下为自己所写代码:

#include "stdafx.h"
#include <iostream>
#include <exception>

using namespace std;

int RotateArrayMin(int* array, int low, int high);

int main(int argc, char* argv[])
{
    const int length = 10;
    int array[length] = {15,17,18,3,5,6,7,9,11,12};
    
    int Location = RotateArrayMin(array,0,length-1);
    cout<<array[Location]<<endl;

    return 0;
}

//基本思想:采用折半查找的方法
//        改变搜索规则以及终止条件
//时间复杂度:O(logn)
int RotateArrayMin(int* array, int low, int high)
{
    int SepValue = array[0];

    while(low < high)
    {
        int mid = (low + high)/2;
        if(array[mid] > SepValue)
            low = mid + 1;
        else if(array[mid] < SepValue)
            high = mid;
        else
            throw new std::exception("Values are not increasing!");
    }

    if(low == high)
    {
        if(array[low] > SepValue)
            return low+1;
        else
            return low;
    }
}

 相比较于作者代码,自己弱爆了。。。

考虑问题很不全面。。。

要考虑的问题:

1、排序序列本身可视为特殊的旋转数组,即0旋转数组;

2、即使‘递增’,也要考虑数组中有相同数字的情形。

 作者代码如下:

#include "stdafx.h"
#include<exception>

int MinInOrder(int* numbers, int index1, int index2);

int Min(int* numbers, int length)
{
    if(numbers == NULL || length <= 0)
        throw new std::exception("Invalid parameters");
 
    int index1 = 0;
    int index2 = length - 1;
    int indexMid = index1;
    while(numbers[index1] >= numbers[index2])
    {
        // 如果index1和index2指向相邻的两个数,
        // 则index1指向第一个递增子数组的最后一个数字,
        // index2指向第二个子数组的第一个数字,也就是数组中的最小数字
        if(index2 - index1 == 1)
        {
            indexMid = index2;
            break;
        }
 
        // 如果下标index1、index2和indexMid指向的三个数字相等,
        // 则只能顺序查找
        indexMid = (index1 + index2) / 2;
        if(numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1])
            return MinInOrder(numbers, index1, index2);

        // 缩小查找范围
        if(numbers[indexMid] >= numbers[index1])
            index1 = indexMid;
        else if(numbers[indexMid] <= numbers[index2])
            index2 = indexMid;
    }
 
    return numbers[indexMid];
}

int MinInOrder(int* numbers, int index1, int index2)
{
    int result = numbers[index1];
    for(int i = index1 + 1; i <= index2; ++i)
    {
        if(result > numbers[i])
            result = numbers[i];
    }

    return result;
}

 

posted on 2013-08-08 21:40  -赶鸭子上架-  阅读(222)  评论(0编辑  收藏  举报