|
| 1 | +# Time: O(pf * l + nf * l + n * l + klogk) |
| 2 | +# Space: O(pf * l + nf * l + n) |
| 3 | + |
| 4 | +import random |
| 5 | +import itertools |
| 6 | + |
| 7 | + |
| 8 | +# quick select, partial sort |
| 9 | +class Solution(object): |
| 10 | + def topStudents(self, positive_feedback, negative_feedback, report, student_id, k): |
| 11 | + """ |
| 12 | + :type positive_feedback: List[str] |
| 13 | + :type negative_feedback: List[str] |
| 14 | + :type report: List[str] |
| 15 | + :type student_id: List[int] |
| 16 | + :type k: int |
| 17 | + :rtype: List[int] |
| 18 | + """ |
| 19 | + def nth_element(nums, n, compare=lambda a, b: a < b): |
| 20 | + def tri_partition(nums, left, right, target, compare): |
| 21 | + mid = left |
| 22 | + while mid <= right: |
| 23 | + if nums[mid] == target: |
| 24 | + mid += 1 |
| 25 | + elif compare(nums[mid], target): |
| 26 | + nums[left], nums[mid] = nums[mid], nums[left] |
| 27 | + left += 1 |
| 28 | + mid += 1 |
| 29 | + else: |
| 30 | + nums[mid], nums[right] = nums[right], nums[mid] |
| 31 | + right -= 1 |
| 32 | + return left, right |
| 33 | + |
| 34 | + left, right = 0, len(nums)-1 |
| 35 | + while left <= right: |
| 36 | + pivot_idx = random.randint(left, right) |
| 37 | + pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare) |
| 38 | + if pivot_left <= n <= pivot_right: |
| 39 | + return |
| 40 | + elif pivot_left > n: |
| 41 | + right = pivot_left-1 |
| 42 | + else: # pivot_right < n. |
| 43 | + left = pivot_right+1 |
| 44 | + |
| 45 | + pos, neg = set(positive_feedback), set(negative_feedback) |
| 46 | + arr = [] |
| 47 | + for i, r in itertools.izip(student_id, report): |
| 48 | + score = sum(3 if w in pos else -1 if w in neg else 0 for w in r.split()) |
| 49 | + arr.append((-score, i)) |
| 50 | + nth_element(arr, k-1) |
| 51 | + return [i for _, i in sorted(arr[:k])] |
0 commit comments