谷歌面試題 資料流的中值

2021-06-09 20:14:37 字數 2417 閱讀 4213

谷歌面試題 資料流的中值:設計和實現一種資料結構能支援兩種操作,insert(value)和getmedian()。in english, design and implement a collection that supports two operations: insert(value) and getmedian().

#include #include "testing/gtest/include/gtest/gtest.h"

template char (&arraysizehelper(const t (&array)[n]))[n];

#define arraysize(array) (sizeof(arraysizehelper(array)))

class mediancollection

else

if(set_.size()== 2)

else

// has two medians before insertion.

else

} } }

//according to the definition of median. if n is even, then

//median (m) = value of [((n)/2)th item term + ((n)/2 + 1)th item term ]/2

//in our case, we provide the two medians.

int smallermedian() const

int biggermedian() const

//alias of smallmedian and biggermedian when only one median exists.

int median() const

bool hastwomedian() const

bool empty() const

private:

//set is usually implemented as a red-black tree

std::setset_;

//bigger median.

int smaller_median_;

//smaller median.

int bigger_median_;

};void test1()

; for(int i= 0; i< arraysize(input); i++)

coll.insert(input[i]);

expect_eq(coll.median(), 3);

expect_false(coll.hastwomedian());

expect_false(coll.empty());

expect_eq(coll.median(),coll.biggermedian());

expect_eq(coll.median(),coll.smallermedian());

}void test2()

; for(int i= 0; i< arraysize(input); i++)

coll.insert(input[i]);

expect_eq(coll.median(), 3);

expect_false(coll.hastwomedian());

expect_false(coll.empty());

expect_eq(coll.median(),coll.biggermedian());

expect_eq(coll.median(),coll.smallermedian());

}void test3()

; for(int i= 0; i< arraysize(input); i++)

coll.insert(input[i]);

expect_eq(coll.smallermedian(), 3);

expect_eq(coll.biggermedian(), 4);

expect_true(coll.hastwomedian());

expect_false(coll.empty());

}void test4()

; for(int i= 0; i< arraysize(input); i++)

coll.insert(input[i]);

expect_eq(coll.smallermedian(), 3);

expect_eq(coll.biggermedian(), 4);

expect_true(coll.hastwomedian());

expect_false(coll.empty());

}void test5()

void test6()

int main(int argc, char* argv)

面試題41 資料流中的中位數

題目 解答 方法一 c 超時 1 class medianfinder 1011 returns the median of current data stream 12double findmedian 1319 方法二 二分查詢插入 方法一的缺點在於對陣列進行了排序操作,導致時間複雜度較高,假如...

谷歌面試題

這個所謂的面試沒有物理存在,只是邏輯上等同於。題目要求如下 整數序列q中的每個元素都至少能被整數a和b中的乙個整除,現給定a和b,請計算出q中的前n項元素。例如,當a 3,b 5,n 6時,q序列的前6項元素為3,5,6,9,10,12。1 設計函式void generate int a int b...

谷歌面試題

某獵頭收集了140多個google的面試題,都張到他的blog中了,主要是下面這些職位的,因為被牆,且無任何敏感資訊,所以,我原文搬過來了。這篇blog例舉了google用來面試下面這幾個職位的面試題。很多不是很容易回答,不過都比較經典與 是google,microsoft,amazon之類的公司的...