标签:
题目来源: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)
标签:
原文地址:http://www.cnblogs.com/hslzju/p/5621668.html