给定整数n和m, 将1到n的这n个整数按字典序排列之后, 求其中的第m个数。

自己构造了一个map,自定义了map的比较函数,代码通过率为50%,不知道为什么这样的复杂度还不能通过?

代码如下

#include 
#include 
#include 
#include 
using namespace std;

class Compare
{
public:
	bool operator ()(const int i1, const int i2)
	{
		stack stack1;
		stack stack2;

		CutNunber(i1, stack1);
		CutNunber(i2, stack2);
		while (!stack1.empty() && !stack2.empty())
		{
			if (stack1.top() != stack2.top())
			{
				return stack1.top() < stack2.top();
			}
			stack1.pop();
			stack2.pop();
		}
		if (stack1.empty())
		{
			return true;
		}
		else
		{
			return false;
		}
	}
private:
	void CutNunber(const int iNum, stack &stackResult)
	{
		int iTemp = iNum;
		while (iTemp / 10 != 0)
		{
			stackResult.push(iTemp % 10);
			iTemp = iTemp / 10;
		}
		stackResult.push(iTemp);
	}
};

typedef map mapDictinary;

int main()
{
	int m;
	int n;
	cin >> n >> m; 

	mapDictinary mapData;
	for (int i = 1; i <= n; i++)
	{
		mapData.insert(make_pair(i, i));
	}

	mapDictinary::iterator it = mapData.begin();
    if (m == 1)
    {
        cout << it->first;
    }
    else
    {
        while (m != 1)
	    {
		    m--;
		    it++;
	    }
    }

	cout << it->first;
	return 0;
}

你可能感兴趣的:(给定整数n和m, 将1到n的这n个整数按字典序排列之后, 求其中的第m个数。)