Day 16 排序(初级)
Q1 把数组排成最小的数
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
解题思路:本质是排序,但判断大小不能简单地看数值大小,而是要看两个数字组合的不同顺序所构成数的大小
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string> strs;
for(int i = 0; i < nums.size(); i++)
strs.push_back(to_string(nums[i])); //字符串数组
quickSort(strs, 0, strs.size() - 1); //排序
string res;
for(string s : strs)
res.append(s); //字符串数组->字符串
return res;
}
private:
void quickSort(vector<string>& strs, int l, int r) {
if(l >= r) return;
int i = l, j = r;
while(i < j) {
while(strs[j] + strs[l] >= strs[l] + strs[j] && i < j) j--;
while(strs[i] + strs[l] <= strs[l] + strs[i] && i < j) i++;
swap(strs[i], strs[j]);
}
swap(strs[i], strs[l]);
quickSort(strs, l, i - 1);
quickSort(strs, i + 1, r);
}
};
Q2 扑克牌中的顺子
从若干副扑克牌中随机抽 5 张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。
简单排序一下,然后分支判断即可解决。
class Solution {
public:
bool isStraight(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
int zero = 0;
for(int i=0;i<n;i++)
{
if(nums[i]==0) zero++;
else if(i==0||nums[i-1]==0) continue;
else if (nums[i]==nums[i-1]+1) continue;
else{
int tmp = nums[i] - nums[i-1] - 1;
if(tmp>0&&tmp<=zero) zero -= tmp;
else return false;
}
}
return true;
}
};