Find Median from Data Stream
הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.
ממשו את המחלקה MedianFinder, שמקבלת מספרים אחד אחד ויכולה לדווח את החציון (median) שלהם בכל רגע:
new MedianFinder()מתחילה בלי מספרים.addNum(num)מוסיפה מספר שלם.findMedian()מחזירה את החציון של כל המספרים שנוספו עד עכשיו. תשובות בטווח10^-5מהחציון האמיתי מתקבלות.
הבנת הבעיה
- החציון הוא הערך האמצעי אחרי שממיינים את המספרים. ל-
[2, 3, 4]הוא3. - אם יש מספר זוגי של ערכים, יש שני ערכים אמצעיים, והחציון הוא הממוצע שלהם. ל-
[2, 3]הוא2.5. - המספרים מגיעים אחד אחד ("data stream", זרם נתונים), בכל סדר, ואפשר לקרוא ל-
findMedianבין כל שתי הוספות. אז העבודה חייבת להיות מהירה בכל קריאה, לא רק פעם אחת בסוף.
דוגמה 1
ops: ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
args: [[], [1], [2], [], [3], []]
expected: [null, null, null, 1.5, null, 2]- אחרי הוספת
1ו-2: ממוין[1, 2], שני ערכים אמצעיים, חציון(1 + 2) / 2 = 1.5. - אחרי הוספת
3: ממוין[1, 2, 3], חציון2.
איך הטסטים עובדים: כל טסט הוא רצף של קריאות. ops נותן שם לכל קריאה (הראשונה יוצרת את האובייקט), args מחזיק את הארגומנטים, ו-expected את ערכי ההחזרה.
אילוצים
-10^5 <= num <= 10^5- קוראים ל-
findMedianרק אחרי לפחותaddNumאחד. - לכל היותר
5 * 10^4קריאות בסך הכל.
רמזים
נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.
הרעיון במשפט אחד
שומרים את החצי הקטן של המספרים ב-max-heap ואת החצי הגדול ב-min-heap, מאוזנים בגודל, כך שהחציון תמיד יושב בראש של אחד ה-heaps או של שניהם.
הגישה הנאיבית (ולמה היא איטית)
שומרים את כל המספרים במערך ממוין. findMedian רק קוראת את האמצע: O(1). אבל addNum חייבת להכניס את המספר למקום הנכון, וזה מזיז כל איבר שאחריו: O(n) לכל קריאה. עם 50,000 קריאות, זה בערך מיליארד הזזות.
מה זה heap?
heap (ערימה) הוא מבנה שתמיד יודע מה הפריט שבראש שלו:
- min-heap נותן לכם את הפריט הקטן ביותר שלו מיד, ו-
- max-heap נותן לכם את הפריט הגדול ביותר שלו מיד.
הוספת פריט או הוצאת הראש לוקחות O(log n). זה עושה את זה בלי למיין הכל: הוא שומר רק מספיק סדר כדי לדעת מה בראש. (המדריך למתחילים מראה איך זה עובד מבפנים.)
התובנה המרכזית
כדי למצוא את החציון לא צריך הכל ממוין. צריך רק את הערך האחד או השניים שבאמצע. אז מחלקים את המספרים לשני חצאים:
lowמחזיק את החצי הקטן, ב-max-heap. הראש שלו הוא הגדול ביותר מבין המספרים הקטנים.highמחזיק את החצי הגדול, ב-min-heap. הראש שלו הוא הקטן ביותר מבין המספרים הגדולים.
sorted: 1 2 3 | 4 5
└─ low ─┘ └ high ┘
top of low = 3 top of high = 4שומרים על שני חוקים:
- כל מה שב-
lowהוא<=מכל מה שב-high. - הגדלים שווים, או של-
lowיש אחד יותר.
אז שני הערכים האמצעיים הם בדיוק שני הראשים:
- מספר אי-זוגי: החציון הוא הראש של
low. - מספר זוגי: החציון הוא
(הראש של low + הראש של high) / 2.
הוספת מספר תוך שמירה על החוקים:
- דוחפים אותו ל-
low. - מעבירים את הראש של
low(הגדול ביותר שלו) ל-high. זה מתקן את חוק 1: אם המספר החדש היה גדול מדי לחצי הקטן, הוא עכשיו בצד הגדול. - אם
highעכשיו גדול מ-low, מעבירים את הראש שלhigh(הקטן ביותר שלו) בחזרה ל-low. זה מתקן את חוק 2.
צעד אחר צעד
דוגמה 1:
| פעולה | low (max-heap) | high (min-heap) | חציון |
|---|---|---|---|
addNum(1): דוחפים 1 ל-low, מעבירים 1 ל-high, high גדול יותר אז מחזירים 1 | [1] | [] | |
addNum(2): דוחפים 2 ל-low, מעבירים 2 ל-high | [1] | [2] | |
findMedian() | ראש 1 | ראש 2 | (1 + 2) / 2 = 1.5 |
addNum(3): דוחפים 3 ל-low, מעבירים 3 ל-high, high גדול יותר אז מחזירים 2 | [2, 1] | [3] | |
findMedian() | ראש 2 | אי-זוגי ← 2 |
הקוד
הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.
- Python:
heapqמספק רק min-heap. כדי לקבל max-heap, שומרים את המספרים בסימן הפוך (-num): הערך ההפוך הקטן ביותר הוא המקורי הגדול ביותר. - JavaScript/TypeScript: אין heap מובנה, אז הפתרון כולל אחד קטן. זה מערך שבו לפריט באינדקס
iיש ילדים ב-2i + 1וב-2i + 2.pushמוסיף בסוף ו"מבעבע למעלה" כל עוד הוא מנצח את ההורה שלו;popמעביר את הפריט האחרון לראש ו"מוריד" אותו למטה. היכולת לכתוב את זה היא ציפייה נפוצה בראיונות JavaScript.
כמה זה מהיר?
addNum: O(log n), כמה דחיפות והוצאות מ-heap.findMedian: O(1), רק קריאה של הראשים.- זיכרון: O(n) כדי לשמור את כל המספרים.
טעויות נפוצות
- להכניס את המספר החדש ישר ל-heap ה"נכון" על ידי השוואה. זה יכול לעבוד, אבל קל לטעות. השגרה "דוחפים ל-low, מעבירים את הראש ל-high, מאזנים" תמיד נכונה.
- חלוקת מספרים שלמים במקרה הזוגי. התשובה יכולה להיות
1.5: ודאו שאתם מחלקים כמספר עשרוני (ב-Python,/ולא//). - לשכוח להפוך את הסימן בחזרה ב-Python כשקוראים את הראש של
low.
להעמקה
- שני heaps בשביל "האמצע" היא תבנית שאפשר להשתמש בה שוב: חציון בחלון נע, או איזון של שתי קבוצות כשפריטים מגיעים.
- שאלת המשך: אם כל המספרים בין 0 ל-100, מערך פשוט של 101 מונים מהיר עוד יותר: סופרים כל ערך, ועוברים על המונים כדי למצוא את האמצע.
פתרון לדוגמה
/**
* A binary heap stored in an array: the item at index i has children at 2i + 1 and 2i + 2.
* `before(a, b)` is true when `a` belongs closer to the top.
*/
class Heap {
items = []
constructor(before) {
this.before = before
}
get size() {
return this.items.length
}
peek() {
return this.items[0]
}
push(value) {
const items = this.items
items.push(value) // add at the end...
let i = items.length - 1
// ...then bubble it up while it beats its parent.
while (i > 0) {
const parent = (i - 1) >> 1
if (!this.before(items[i], items[parent])) break
;[items[i], items[parent]] = [items[parent], items[i]]
i = parent
}
}
pop() {
const items = this.items
const top = items[0] // the item we'll return
const last = items.pop()
if (items.length > 0) {
// Move the last item to the top, then sink it down to where it belongs.
items[0] = last
let i = 0
while (true) {
const left = 2 * i + 1
const right = left + 1
let best = i // whichever of node, left child, right child belongs on top
if (left < items.length && this.before(items[left], items[best])) best = left
if (right < items.length && this.before(items[right], items[best])) best = right
if (best === i) break
;[items[i], items[best]] = [items[best], items[i]]
i = best
}
}
return top
}
}
export default class MedianFinder {
low = new Heap((a, b) => a > b) // max-heap: the smaller half, its top is its largest
high = new Heap((a, b) => a < b) // min-heap: the larger half, its top is its smallest
/**
* @param {number} num
* @return {void}
*/
addNum(num) {
this.low.push(num)
// Move the largest of the small half across: now everything in low <= everything in high.
this.high.push(this.low.pop())
// Keep the sizes balanced, with low allowed one extra.
if (this.high.size > this.low.size) this.low.push(this.high.pop())
}
/**
* @return {number}
*/
findMedian() {
// Odd count: the middle value is low's top.
if (this.low.size > this.high.size) return this.low.peek()
// Even count: average the two middle values.
return (this.low.peek() + this.high.peek()) / 2
}
}/**
* A binary heap stored in an array: the item at index i has children at 2i + 1 and 2i + 2.
* `before(a, b)` is true when `a` belongs closer to the top.
*/
class Heap {
private items: number[] = []
constructor(private before: (a: number, b: number) => boolean) {}
get size(): number {
return this.items.length
}
peek(): number {
return this.items[0]
}
push(value: number): void {
const items = this.items
items.push(value) // add at the end...
let i = items.length - 1
// ...then bubble it up while it beats its parent.
while (i > 0) {
const parent = (i - 1) >> 1
if (!this.before(items[i], items[parent])) break
;[items[i], items[parent]] = [items[parent], items[i]]
i = parent
}
}
pop(): number {
const items = this.items
const top = items[0] // the item we'll return
const last = items.pop()!
if (items.length > 0) {
// Move the last item to the top, then sink it down to where it belongs.
items[0] = last
let i = 0
while (true) {
const left = 2 * i + 1
const right = left + 1
let best = i // whichever of node, left child, right child belongs on top
if (left < items.length && this.before(items[left], items[best])) best = left
if (right < items.length && this.before(items[right], items[best])) best = right
if (best === i) break
;[items[i], items[best]] = [items[best], items[i]]
i = best
}
}
return top
}
}
export default class MedianFinder {
private low = new Heap((a, b) => a > b) // max-heap: the smaller half, its top is its largest
private high = new Heap((a, b) => a < b) // min-heap: the larger half, its top is its smallest
addNum(num: number): void {
this.low.push(num)
// Move the largest of the small half across: now everything in low <= everything in high.
this.high.push(this.low.pop())
// Keep the sizes balanced, with low allowed one extra.
if (this.high.size > this.low.size) this.low.push(this.high.pop())
}
findMedian(): number {
// Odd count: the middle value is low's top.
if (this.low.size > this.high.size) return this.low.peek()
// Even count: average the two middle values.
return (this.low.peek() + this.high.peek()) / 2
}
}import heapq
class MedianFinder:
def __init__(self):
# heapq is a min-heap only. Storing -num turns it into a max-heap.
self.low = [] # max-heap of the smaller half, stored negated
self.high = [] # min-heap of the larger half
def add_num(self, num: int) -> None:
heapq.heappush(self.low, -num)
# Move the largest of the small half across: now everything in low <= everything in high.
heapq.heappush(self.high, -heapq.heappop(self.low))
# Keep the sizes balanced, with low allowed one extra.
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def find_median(self) -> float:
# Odd count: the middle value is low's top (negate it back).
if len(self.low) > len(self.high):
return -self.low[0]
# Even count: average the two middle values.
return (-self.low[0] + self.high[0]) / 2