• [容易]中位数


    题目来源:http://www.lintcode.com/zh-cn/problem/median/

    C++版 VS2012测试通过

    方法一

     1 class Solution {
     2 public:
     3     /**
     4      * @param nums: A list of integers.
     5      * @return: An integer denotes the middle number of the array.
     6      */
     7     int median(vector<int> &nums) {
     8         // write your code here
     9         sort(nums.begin(),nums.end());
    10         if(nums.size()%2==0)
    11             return nums.at(nums.size()/2-1);
    12         else
    13             return nums.at((nums.size()-1)/2);
    14     }
    15 };

    方法二

     1 class Solution {
     2 public:
     3     /**
     4      * @param nums: A list of integers.
     5      * @return: An integer denotes the middle number of the array.
     6      */
     7     int median(vector<int> &nums) {
     8         // write your code here
     9         int k = (nums.size() + 1) / 2;
    10         priority_queue<int> que;
    11         int len = nums.size();
    12         for(int i = 0; i < len; i ++) {
    13             if(que.size() == k) {
    14                 if(nums[i] < que.top()) {
    15                     que.pop();
    16                     que.push(nums[i]);
    17                 }
    18             }else {
    19                 que.push(nums[i]);
    20             }
    21         }
    22         return que.top();
    23     }
    24 };

    Python2.7版 spider测试通过

     1 class Solution:
     2     """
     3     @param nums: A list of integers.
     4     @return: An integer denotes the middle number of the array.
     5     """
     6     def median(self, nums):
     7         # write your code here
     8         nums.sort()
     9         return nums[(len(nums)-1)/2]
    10 
    11 #测试
    12 #if __name__=='__main__':
    13 #    n=[4,5,7,9]
    14 #    s=Solution()
    15 #    print s.median(n) 
  • 相关阅读:
    bash task list and interrupt
    bash字符串大小写转换方法
    Spectrum Mask
    OFDM中CP的优缺点
    模块边界使用寄存器来做数据的交互
    跨时钟域信号处理
    FPGA中一个Slice所含资源
    Verilog中if-else改写成case的方法
    同步序列的自相关与互相关
    TCP三次握手四次挥手
  • 原文地址:https://www.cnblogs.com/hslzju/p/5621668.html
Copyright © 2020-2023  润新知