剑指Offer-第16天 排序(简单)

第一题

题目链接:https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/

个人题解:按照字符串相加小的来排序即可

代码:

class Solution {
public:
    string minNumber(vector<int>& nums) {
        vector<string> vec;
        for(auto x:nums) vec.push_back(to_string(x));

        sort(vec.begin(),vec.end(),[&](auto a,auto b){
            return a+b<b+a;
        });

        string res;
        for(auto x:vec) res+=x;
        return res;
    }
};

image

第二题

题目链接:https://leetcode.cn/problems/bu-ke-pai-zhong-de-shun-zi-lcof/

个人题解:

  1. 不能相邻一样
  2. 相邻两数的差值不能超过 \(0\) 的个数

代码:

class Solution {
public:
    bool isStraight(vector<int>& nums) {
        sort(nums.begin(),nums.end());

        int cnt=0;
        for(int i=0;i<4;i++){
            if(nums[i]==0) cnt++;
            else{
                if(nums[i+1]==nums[i]) return false;
                if(nums[i+1]-nums[i]-1>cnt) return false;
                cnt-=(nums[i+1]-nums[i]-1);
            }
        }
        return true;
    }
};

运行截图:

image

posted @ 2022-05-18 22:42  黑VS白-清墨  阅读(19)  评论(0)    收藏  举报