自以为想到了一个简单方法,代码如下:
class Solution { public: int getKth(int lo, int hi, int k) { unordered_map<int, int> step_map; vector<pair<int, int>> weights; for (int i=lo; i<=hi; i++) { weights.emplace_back(pair<int,int>{i,calcuStep(step_map,i)}); } sort(weights.begin(), weights.end(), [=](pair<int, int> a, pair<int, int> b){ if (a.second!=b.second){ return a.second<b.second; } else { return a.first<b.first; } }); return weights[k-1].first; } int calcuStep(unordered_map<int, int>& step_map, int val) { vector<int> num_in_process; auto itr = step_map.find(val); if (itr!=step_map.end()) { return itr->second; } int step_num = 0; while(val != 1) { num_in_process.emplace_back(val); if (val%2 == 0) { val = val/2; } else { val = val*3 +1; } step_num++; itr = step_map.find(val); if (itr!=step_map.end()) { step_num += itr->second; for (int i=0; i< num_in_process.size(); i++) { step_map[num_in_process[i]] = step_num-i; } return step_num; } } return step_num; } };
思想就是使用记忆,代码编写和调试耗时一小时多,但看了答案后发现写的好low,答案是用递归写的,看着就漂亮
class Solution { public: int getKth(int lo, int hi, int k) { unordered_map<int, int> weights_map; vector<pair<int,int>> weights; for (int i=lo; i<=hi; i++) { weights.emplace_back(pair<int,int>{i,F(weights_map,i)}); } sort(weights.begin(), weights.end(), [=](pair<int, int> a, pair<int, int> b) { if (a.second == b.second) { return a.first<b.first; } else { return a.second<b.second; } }); return weights[k-1].first; } int F(unordered_map<int, int>& weights_map, int num) { if (num==2) { return 1; } if (weights_map.find(num)!=weights_map.end()) { return weights_map[num]; } if (num & 1) { return weights_map[num] = 1+ F(weights_map,3*num+1); } else { return weights_map[num] = 1+F(weights_map,num/2); } } };