leetcode869. 重新排序得到 2 的幂
生活随笔
收集整理的這篇文章主要介紹了
leetcode869. 重新排序得到 2 的幂
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目連接:https://leetcode-cn.com/problems/reordered-power-of-2/
題目分析
如果直接順著題目的思路,得到數(shù)字n的全排列,然后再去判斷其是不是2的冪是比較復(fù)雜的。
我們應(yīng)該注意到,因為數(shù)字是可以隨意排列的,因此所有可以通過變換排列得到的數(shù)字都有相同個數(shù)的0、1、2,而n?1e9n\leqslant1e9n?1e9,2的冪只有30個左右,我們可以先記錄2的冪次然后再判斷當(dāng)前數(shù)字是不是和這些數(shù)字有相同的數(shù)字組合。
AC代碼
class Int {static constexpr int MAXN = 10; public:explicit Int(int x = 0);array<int, MAXN> cnt;friend bool operator == (const Int &lhs, const Int &rhs); };Int::Int(int x):cnt({0}) {while (x) {++cnt[x % 10];x /= 10;} }bool operator == (const Int &lhs, const Int &rhs) {return lhs.cnt == rhs.cnt; }void init(vector<Int> &pow) {constexpr int MAXN = 1e9;int x = 1;while (x < MAXN) {pow.emplace_back(x);x <<= 1;} }class Solution { public:bool reorderedPowerOf2(int n) {vector<Int> pow;init(pow);Int nn(n);for (auto &integer : pow) {if (integer == nn) return true;}return false;} };題解分析
剛開始的時候考慮要不要使用二分查找,但是覺得這樣的話還得排序,還得預(yù)處理,每次運行樣例的時候都得處理一遍好像意義不大。
看了一下題解,發(fā)現(xiàn)題解在全局進(jìn)行預(yù)處理,使用了匿名函數(shù),第一次在C++里面見到這樣使用匿名函數(shù),的確很方便。
int i = []() -> int {cout << "Hello world" << endl;return 0; }();并且題解將數(shù)字映射成了一個字符串,這樣就可以使用unorder_map進(jìn)行O(1)O(1)O(1)查詢,感覺還是很巧妙的。
總結(jié)
以上是生活随笔為你收集整理的leetcode869. 重新排序得到 2 的幂的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成都大熊猫繁育基地下午能看见熊猫吗
- 下一篇: 使用wireshark+ssh+tcpd