首页 > 试题广场 >

1029. Median (25)

[编程题]1029. Median (25)
  • 热度指数:3948 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.
Given two increasing sequences of integers, you are asked to find their median.

输入描述:
Each input file contains one test case.  Each case occupies 2 lines, each gives the information of a sequence.  For each sequence, the first positive integer N (<=1000000) is the size of that sequence.  Then N integers follow, separated by a space.  It is guaranteed that all the integers are in the range of long int.


输出描述:
For each test case you should output the median of the two given sequences in a line.
示例1

输入

4 11 12 13 14
5 9 10 15 16 17

输出

13
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = sorted(a[1:] + b[1:])
print(c[(a[0] + b[0] - 1) // 2])
原代码pta上最后一个用例极难通过(10次碰上一次不超时)
a = list(map(int,input().split()))
b = list(map(int,input().split()))

if a[(a[0] + 1) // 2] > b[(b[0] + 1) // 2]:
    a,b = b,a
if a[-1] > b[1]:
    c = sorted(a[(a[0] + 1) // 2:] + b[1:(b[0] + 1) // 2 + 1])
    print(c[(a[0] + b[0] + 1) // 2 - (a[0] + 1) // 2])
else:
    if a[0] >= b[0]:
        print(a[(a[0] + b[0] + 1) // 2])
    else:
        print(b[(a[0] + b[0] + 1) // 2 - a[0]])
改了之后提交10次碰上1次超时



编辑于 2020-02-07 13:41:07 回复(0)
排序的时间复杂度的下限是Nlog(N),那我就用堆吧
import heapq
nums=[]
nums.extend(map(int,raw_input().split())[1:])
nums.extend(map(int,raw_input().split())[1:])
print heapq.nsmallest((len(nums)+1)/2,nums)[-1]
发表于 2019-01-16 14:15:03 回复(0)