给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入: [10,2]
输出: 210
示例 2:
输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
class Solution {
public:
string largestNumber(vector<int>& nums) {
if (nums.size() == 0) return "";
auto cmp = [](string& a, string& b) { //
return a + b > b + a;
};
vector<string> vec_str;
for (auto &n: nums) {
vec_str.push_back(to_string(n));
}
sort(vec_str.begin(), vec_str.end(), cmp);
string res;
for (auto &v: vec_str) {
res += v;
}
return res[0] == '0' ? "0" : res; // 0...0情况
}
};
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
示例 1:
输入: [5,7]
输出: 4
示例 2:
输入: [0,1]
输出: 0
class Solution { // 我们可以将问题重新表述为:给定两个整数,我们要找到它们对应的二进制字符串的公共前缀
public:
int rangeBitwiseAnd(int m, int n) {
while (m < n) {
n = n&(n - 1); // 去除n最右边的1
}
return n;
}
/*
int rangeBitwiseAnd(int m, int n) {
int shift = 0;
while (m < n) {
m >>= 1;
n >>= 1;
++shift;
}
return m << shift;
}
*/
};
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:
输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:
给定数组的长度不会超过15。
数组中的整数范围是 [-100,100]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
class Solution {
vector<vector<int>> res;
vector<int> path;
vector<int> sel;
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
if (nums.empty()) return {};
sel = nums;
backTrack(0);
return res;
}
void backTrack(const int& start) {
if (path.size() > 1) { //
res.push_back(path);
}
if (start == sel.size()) {
return;
}
unordered_set<int> s;
for (int i = start; i < sel.size(); ++i) {
if (path.size() && sel[i] < path.back()) continue;
if (s.count(sel[i])) continue; //
s.insert(sel[i]);
// 错误:
// 初始化:last = -1
// if (last != -1 && sel[i] == sel[last]) continue;
// last = i;
path.push_back(sel[i]);
backTrack(i + 1);
path.pop_back();
}
}
};
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
示例 2:
输入: 28
输出: "AB"
示例 3:
输入: 701
输出: "ZY"
class Solution {
public:
/*
string convertToTitle(int n) {
string res;
while (n) {
res = static_cast<char>((n - 1)%26 + 'A' ) + res; // { (n - 1)%26 + 1 <-> n%26 } - 1
n = (n - 1)/26;
}
return res;
}*/
string convertToTitle(int n) {
string res;
while (n) {
--n; // 0~25 <-> A~Z
res = static_cast<char>(n%26 + 'A') + res;
n /= 26;
}
return res;
}
};