zoukankan      html  css  js  c++  java
  • [容易]中位数

    题目来源: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) 
  • 相关阅读:
    水利行业传感器
    含水量传感器
    水位传感器
    物联网实践
    SQLCMD
    zigbee
    物联网支撑平台
    近距通信技术比较
    物联网发展
    NFC标签
  • 原文地址:https://www.cnblogs.com/hslzju/p/5621668.html
Copyright © 2011-2022 走看看