设为首页 加入收藏

TOP

C++ 和 Python 实现旋转数组的最小数字(四)
2019-02-07 22:08:02 】 浏览:340
Tags:Python 实现 旋转 最小 数字
include files that are used frequently, but
// are changed infrequently
//


#pragma once


#include "targetver.h"


#include <stdio.h>
#include <tchar.h>


// TODO: reference additional headers your program requires here


3. stdafx.cpp


// stdafx.cpp : source file that includes just the standard includes
// MinNumberInRotatedArray.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information


#include "stdafx.h"


// TODO: reference any additional headers you need in STDAFX.H
// and not in this file


4. MinNumberInRotatedArray.cpp


// MinNumberInRotatedArray.cpp : Defines the entry point for the console application.
//


// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛


#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;
}


// ====================测试代码====================
void Test(int* numbers, int length, int expected)
{
    int result = 0;
    try
    {
        result = Min(numbers, length);


        for(int i = 0; i < length; ++i)
            printf("%d ", numbers[i]);


        if(result == expected)
            printf("\tpassed\n");
        else
            printf("\tfailed\n");
    }
    catch (...)
    {
        if(numbers == NULL)
            printf("Test passed

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++ STL容器——stack用法介绍 下一篇C++随机排序容器中的元素

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目