題目連接:https://leetcode-cn.com/problems/reordered-power-of-2/
題目分析
如果直接順著題目的思路,得到數字n的全排列,然后再去判斷其是不是2的冪是比較復雜的。
我們應該注意到,因為數字是可以隨意排列的,因此所有可以通過變換排列得到的數字都有相同個數的0、1、2,而n?1e9n\leqslant1e9n?1e9,2的冪只有30個左右,我們可以先記錄2的冪次然后再判斷當前數字是不是和這些數字有相同的數字組合。
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;}
};
題解分析
剛開始的時候考慮要不要使用二分查找,但是覺得這樣的話還得排序,還得預處理,每次運行樣例的時候都得處理一遍好像意義不大。
看了一下題解,發現題解在全局進行預處理,使用了匿名函數,第一次在C++里面見到這樣使用匿名函數,的確很方便。
int i = []() -> int {cout << "Hello world" << endl;return 0;
}();
并且題解將數字映射成了一個字符串,這樣就可以使用unorder_map
進行O(1)O(1)O(1)查詢,感覺還是很巧妙的。