剑指Offer刷题记录 Day_16

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;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值