剑指 Offer 45. 把数组排成最小的数
以 3 、 30 为例
30 3 < 3 30
所以应该将30置于3的前面
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string> strs;
for (auto &num : nums) {
strs.push_back(to_string(num));
}
sort(strs.begin(), strs.end(), [](const string &a, const string& b){
return a + b < b + a;
});
string res;
for (auto &str : strs) {
res += str;
}
return res;
}
};
剑指 Offer 61. 扑克牌中的顺子
排序
class Solution {
public:
bool isStraight(vector<int>& nums) {
sort(nums.begin(), nums.end());
int joker = 0; // 大小王的数量
for (int i = 0; i < 4; i++) {
if (nums[i] == 0) {
joker++;
} else if (nums[i] == nums[i + 1]){
return false;
}
}
return nums[4] - nums[joker] < 5; // 最大数减去最小数是否小于五
}
};
集合
class Solution {
public:
bool isStraight(vector<int>& nums) {
unordered_set<int> us;
int maxNum = 0, minNum = 100;
for (const auto &num : nums) {
if (num == 0)
continue;
maxNum = max(maxNum, num);
minNum = min(minNum, num);
if (us.count(num)) return false;
us.insert(num);
}
return maxNum - minNum < 5; // 最大数减去最小数是否小于五
}
};
剑指 Offer 40. 最小的k个数
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
sort(arr.begin(), arr.end());
vector<int> res;
for (int i = 0; i < k; i++) {
res.push_back(arr[i]);
}
return res;
}
};
剑指 Offer 41. 数据流中的中位数
class MedianFinder {
public:
priority_queue<int, vector<int>, less<int>> queMin;
priority_queue<int, vector<int>, greater<int>> queMax;
MedianFinder() {}
void addNum(int num) {
if (queMin.empty() || num <= queMin.top()) {
queMin.push(num);
if (queMax.size() + 1 < queMin.size()) {
queMax.push(queMin.top());
queMin.pop();
}
} else {
queMax.push(num);
if (queMax.size() > queMin.size()) {
queMin.push(queMax.top());
queMax.pop();
}
}
}
double findMedian() {
if (queMin.size() > queMax.size()) {
return queMin.top();
}
return (queMin.top() + queMax.top()) / 2.0;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/