题解 | 1、【C++】字符串排序

字符串排序

http://www.nowcoder.com/questionTerminal/0425aa0df74646209d3f56f627298ab2

解题思路

  1. 对每次输入的字符串样本,通过substr()得到后六位子串。
  2. 把每个子串通过stoi转换为整型,并把结果插入到容器mutiset中,自动完成排序。
  3. 最后遍历容器mutiset即可得到顺序排列的数据集。

完整代码

#include<iostream>
#include<string>
#include<set>
using namespace std;

int main()
{
    int M=0;
    cin>>M;
    string s;// 获取每个字符串样本
    multiset<int> ms;// ms用来存储后六位数字并排序
    while(M--)
    {
        cin>>s;
        // 1、先通过substr得到后六位纯数字的子串
        // 2、再通过stoi把该子串转为整型并插入到ms中
        ms.insert(stoi(s.substr(s.size()-6)));
    }
    // 最后遍历ms即可得到排序好的数据
    for(auto& e : ms)
    {
        cout<<e<<endl;
    }
    return 0;
}

性能分析

  • 时间复杂度:O(nlogn)。即容器内部排序的时间复杂度O(logn!) = O(nlogn)。
  • 空间复杂度:O(n)。n组数据,创建了n个节点。
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务