题目如下:
We sampled integers between
0
and255
, and stored the results in an arraycount
:count[k]
is the number of integers we sampled equal tok
.Return the minimum, maximum, mean, median, and mode of the sample respectively, as an array of floating point numbers. The mode is guaranteed to be unique.
(Recall that the median of a sample is:
- The middle element, if the elements of the sample were sorted and the number of elements is odd;
- The average of the middle two elements, if the elements of the sample were sorted and the number of elements is even.)
Example 1:
Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0] Output: [1.00000,3.00000,2.37500,2.50000,3.00000]Example 2:
Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0] Output: [1.00000,4.00000,2.18182,2.00000,1.00000]Constraints:
count.length == 256
1 <= sum(count) <= 10^9
- The mode of the sample that count represents is unique.
- Answers within
10^-5
of the true value will be accepted as correct.
解题思路:最大值,最小值,平均数和众数都很简单。中位数我是用两次循环求的,第一次求出样本的个数,根据个数求出中位数的下标,然后第二次循环即可得到。
代码如下:
class Solution(object): def sampleStats(self, count): """ :type count: List[int] :rtype: List[float] """ minv = None maxv = 0 times = sum(count) amount = 0 most = 0 mostCount = 0 inx1 = times / 2 if times % 2 == 0: inx2 = inx1 - 1 else: inx2 = None median1 = 0 median2 = None tmpTimes = 0 for i in range(len(count)): if count[i] != 0 and minv == None: minv = i if count[i] != 0: maxv = i if count[i] != 0: if count[i] > mostCount: most = i mostCount = count[i] if inx1 >= tmpTimes and inx1 <= tmpTimes + count[i]: median1 = i if inx2 != None and inx2 >= tmpTimes and inx2 <= tmpTimes + count[i]: median2 = i tmpTimes += count[i] amount += (count[i]*i) median = median1 if inx2 == None else (float(median2) + float(median1)) / float(2) return [float(minv),float(maxv),float(amount)/float(times),float(median),float(most)]