题解 | #数据流中的中位数#

数据流中的中位数

http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1

使用插入排序保证每次插入后序列都是有序的。同时注意insert方法是在指定迭代器前方插入(而不是在当前迭代器位置插入)!!!

class Solution {
  public:
    //  使用插入排序,每次插入之后都直接是有序序列
    void Insert(int num) {
      if (steam.empty()) {
        steam.push_back(num);
        return ;
      }
      
      int idx = steam.size() - 1;
      
      for (; idx >= 0 && steam[idx] > num; --idx) {
      }
      
      auto it = steam.begin() + idx + 1;
      
      steam.insert(it, num);
    }

    //  本身已经有序
    double GetMedian() { 
      int half_size = steam.size() / 2;
      
      //  奇数个
      if (steam.size() % 2) {
        return static_cast<double>(steam[half_size]);
      } else {
        return static_cast<double>(steam[half_size] + steam[half_size - 1]) / 2;
      }
    }

  private:
    std::vector<int> steam;
};
全部评论

相关推荐

牛马人的牛马人生:一开始看成了网吧
点赞 评论 收藏
分享
10-27 02:29
已编辑
门头沟学院 嵌入式工程师
牛客72783561...:简历不是这么写的,你这两个项目只说了用到了什么技术,却没说取得了什么成果,在我看来这就是你自己做的一个demo,没有价值。你为什么不写你电赛国二的那个项目?
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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