Skip to content

Commit 2bbd8e5

Browse files
authored
Create mean-of-array-after-removing-some-elements.py
1 parent 6f19882 commit 2bbd8e5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time: O(n) on average, using Median of Medians could achieve O(n) (Intro Select)
2+
# Space: O(1)
3+
4+
import random
5+
6+
7+
class Solution(object):
8+
def trimMean(self, arr):
9+
"""
10+
:type arr: List[int]
11+
:rtype: float
12+
"""
13+
P = 20
14+
def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
15+
def tri_partition(nums, left, right, target, compare):
16+
mid = left
17+
while mid <= right:
18+
if nums[mid] == target:
19+
mid += 1
20+
elif compare(nums[mid], target):
21+
nums[left], nums[mid] = nums[mid], nums[left]
22+
left += 1
23+
mid += 1
24+
else:
25+
nums[mid], nums[right] = nums[right], nums[mid]
26+
right -= 1
27+
return left, right
28+
29+
right = len(nums)-1
30+
while left <= right:
31+
pivot_idx = random.randint(left, right)
32+
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
33+
if pivot_left <= n <= pivot_right:
34+
return
35+
elif pivot_left > n:
36+
right = pivot_left-1
37+
else: # pivot_right < n.
38+
left = pivot_right+1
39+
40+
k = len(arr)//P
41+
nth_element(arr, k-1)
42+
nth_element(arr, len(arr)-k, left=k)
43+
return float(sum(arr[i] for i in xrange(k, len(arr)-k)))/(len(arr)-2*k)

0 commit comments

Comments
 (0)