給定整數n和m, 將1到n的這n個整數按字典序排列之後, 求其中的第m個數。
阿新 • • 發佈:2019-02-06
自己構造了一個map,自定義了map的比較函式,程式碼通過率為50%,不知道為什麼這樣的複雜度還不能通過?
程式碼如下
#include <iostream> #include <vector> #include <map> #include <stack> using namespace std; class Compare { public: bool operator ()(const int i1, const int i2) { stack<int> stack1; stack<int> 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<int> &stackResult) { int iTemp = iNum; while (iTemp / 10 != 0) { stackResult.push(iTemp % 10); iTemp = iTemp / 10; } stackResult.push(iTemp); } }; typedef map<int, int, Compare> 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; }