日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

[容易]中位数

發(fā)布時間:2023/12/13 综合教程 31 生活家
生活随笔 收集整理的這篇文章主要介紹了 [容易]中位数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

題目來源: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) 

總結(jié)

以上是生活随笔為你收集整理的[容易]中位数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。