0(n)时间复杂度,找出最接近当前元素的 1)比当前元素大的左元素 2)比当前元素小的右元素

504 篇文章 0 订阅
// o(n)在元素左侧最近位置找出比元素大的数.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <stack>
#include <iterator>

using namespace std;

typedef struct withindex
{
    int value;
    int index;
}WithIndexSt;

typedef struct smallerNum
{
    int curValue;
    int index;
}SmallerNum;

void NearestNumberSmallerThanCurrent(int src[], int dst[], int n)
{
	for (int idx = 0; idx < n; idx++)
		dst[idx] = -1;

	stack<SmallerNum> m_stack;
	for (int i = 0; i < n; i++)
	{
		while(m_stack.size() > 0)
		{
			if (src[i] < m_stack.top().curValue)
			{
				dst[m_stack.top().index] = src[i];
				m_stack.pop();
			}
			else
				break;
		}
		SmallerNum newPair = {src[i],i};
		m_stack.push(newPair);
	}
}

void NearestNumberGreaterThanCurrent(int src[], int dst[], int n)
{
	for (int idx = 0; idx < n; idx++)
		dst[idx] = -1;

    stack<WithIndexSt> m_stack;
    for(int i = n - 1; i >= 0; i--)
    {
        while(!m_stack.empty())
        {
            if(m_stack.top().value < src[i])
            {
                dst[m_stack.top().index] = i;
                m_stack.pop();
            }
            else
                break;
        }
        WithIndexSt tmpst = {src[i], i};
        m_stack.push(tmpst);
    }
}

int main()
{
    int src[] = {2, 9, 5, 2, 4, 1};
    int nsize = sizeof(src)/sizeof(int);
    int* dst = new int[nsize];
    NearestNumberGreaterThanCurrent(src, dst, nsize);
    copy(src, src+nsize, ostream_iterator<int>(cout, "\t"));
    cout<<endl;
    copy(dst, dst+nsize, ostream_iterator<int>(cout, "\t"));
    cout<<endl;
    delete[] dst;

    cout << endl;

    int* dst2 = new int[nsize];
    NearestNumberSmallerThanCurrent(src, dst2, nsize);
    copy(src, src+nsize, ostream_iterator<int>(cout, "\t"));
    cout<<endl;
    copy(dst2, dst+nsize, ostream_iterator<int>(cout, "\t"));
    cout<<endl;
    delete[] dst2;


    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值