LeetCode And LintCode Chapter One

1. LeetCode 56 : Merge Intervals?


Solution:

First sort the array using lambda or comparator defined by yourself. Then loop the array. For every item in the array, compare the start of current item and the end the last item pushed in the result array. Here is the example: [[1, 4], [4, 5]], in this case we should combine two items, in other words, update the end of first item. [[1, 4], [5, 6]], in this case, we could just push the item into result array.

Learned: Python Sort

Sort will not change the list but sorted will change. However, sorted are more powerful since it could sorted by keys, comparators as well as reverse. Keys are helpful according to list elements and its attributes. This techniques is fast because the key function is actually called once for each input record. Example: sorted(student_tuples, key=lambda student: student[2]) . Comparators is much like in c++.? def reverse_numeric(x, y):return y - x sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)?

For lambda, its expression is much like lambda arguments1, argument2.. : return value

2. Top K Problem


Problem1: LeetCode 347 Top K Frequent Elements

Solution:

The context mentioned that the complexity should be better than O(nlogn) so sorting is not the way. Here we have to two solutions. First, in C++, use map + nth_element. The expected running time of nthe_element is O(N). The worst case running time for most implementations is O(N * N) because most implementations use QuickSelect and it could be that QuickSelect runs into bad partitions. Second, in Python, use bucket sort + dict. I really like the nice and succinct code in LeetCode. Here is what he wrote.


LeetCode 347 Python, Bucket Sort

Learned:

1. nth_element complexity is O(n) of expected running time but O(n * n) for the worst cases. ? ??

2. In Python list comprehension: thing for thing in list_of_things: This is a way to construct list ?

3. itertools.chain: Make an iterator that returns elements from the first iterable until it is exhausted and it is used for treating consecutive sequences as a single sequence. So in the case below, it will ignore the empty element.?

4. Counter will count the element frequency and return a dict. dict.items() will return a list whose elements are much like pair(first, second) actually it is a tuple and the first is the element, the second is the frequency.?

5. Bucket Sort: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. In this case, the bucket width is 1. In LeetCode 220 Contains Duplicate III, it is one of the solutions.?

Problem2: LintCode 544 Top k Largest Numbers

Probem3: LintCode 545 Top k Largest Numbers II

Solutions:

C++: Priority_queue plus multiset. Python: Heapy

Learned:

By default, in C++, its comparator returns the same as applying the less-than operator (a < b). It means, it's top is the largest value of current heap. In Python, we use heapy. heapq.nlargest(k, iterable[,key]) will return Return a list with the n largest elements from the dataset defined by iterable; heapq.heapify(x) will transform list x to a heap. The interesting property of a heap is that a[0] is always its smallest element; heapq.heappop(heap), pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0].

3. Contains Duplicate I, II, III?

Solution:

In the 1st and 2nd problem, use set and dict+map. For the third problem, we have constrains: find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

In C++: we create a window whose length is k. The data structure is set. We also have a function called lower_bound which returns iterators first no less than the given value. The value pointed by the iterator returned by this function may also be equivalent to value. Set is actually a BST and it is sorted so we could use lower_bound. We need to find the pos nums[i] ?- t.

In Python, we use bucket sort. The length of bucket constructed by dictionary is setted to t + 1 to avoid case t = 0. Still, we maintains a window which width is k. Every time, we have new item. pos = nums[i]/ width. If it is in the bucket, the array contains duplicated items. If not, try bucket[pos + 1] and bucket[pos - 1] and test the difference is whether smaller than width(t + 1) The idea could be concluded as consecutive buckets covering the range of nums. The width of one bucket is t + 1. If two numbers, the index difference is smaller than k, they are in the same window. If the difference between actual value is smaller than t, then

Two numbers are in the same bucket.

Two numbers are in the neighbor buckets

Learned:

In C++, for set insert functions, the return value is a pair. The first value is a pointer pointing to either the newly inserted element or to the equivalent element already in the set. The second value is true if a new element was inserted or false if an equivalent element already existed.

In Python, range vs xrange. range create a list and it occupies memory. Xrange, mostly fast, it returns a object, like generators, rather than a list.?

4. Permutations Problem

Problem1: Next Permutation/Previous Permutation

Given a list of integers, which denote a permutation. Find the next/ previous permutation in ascending order. It is actually the same problem. We can use the similar way to deal with it. In this section, let us talk about the next permutation.

Solution:

Find the rightmost character in it, which is smaller than its next character. Let us call this character as ‘first character’. Example: 4 2 1 5 6 10 7 9 8. 7 is what we want. Then find the ceiling of the ‘first character’ and its position X. Ceiling is the smallest character on right of ‘first character’, which is greater than ‘first character’. Let us call the ceil character as ‘second character’. Swap the first and second character. Sort X right part numbers in default increasing order.?

Learned:

In Python, else could follow for loops. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. Range could generate list in decreasing order. Example: range(start, end, -1).?

Problem2: Permutation Index I & II

Solution:

The first problem is dealing with unique numbers while the second problem is dealing with the duplicated numbers. For the first problem, we need the rank list of the numbers. We calculate the rank of number and use it to multiply the factorial. Example: 4, 1, 2. 4 is third and there are actually 2 numbers smaller than 4. So 2 * A(2,2) = 4. 1 is the first 0 * A(1,1) and 0 * A(0, 0). Finally, sum plus one is our results. We need to update the ranking list every time.

Here is the key to second problem. When we have duplicate numbers, we need use the all numbers factorials value divide the duplicate numbers factorials. Here is the case. 1, 1, 2, 2, 3, 4. The permutation value is A(6,6) / (A(2,2) * A(2,2)). In such cases, we need a map and updated it every time. Here is the C++ Code.

Permutation index II C++ Part 1


Permutation Index II C++ Part2

Learned:

How to calculate duplicate permutation index?

Problem3: Permutation Sequence

Solution:

The idea is actually reverse of the Problem2. Now, we have the index and we need to generate the sequence. Remember: k = (k - 1) % factorial[n - i - 1] + 1 for every time update.?

Learned:?

Python, change the list to string. "".join([str(i) for i in target_list])

Problem4: Permutations I & II and String Permutation II

Solution:

Permutations II is the problem with duplicated numbers. String Permutation II is just String version of Permutations II. For the first problem, it is a backtracking problem. For the second problem, add the visited vectors for help. Here is the C++ code. Here we need put more attention on the visited[i - 1]. If it is true, we will have much more useless loops. Here is the small case. [1, 1, 1] If we use false, we only need to call helper functions for 8 times while for true, it need 3 times. Here is the visited state in function calling.?

0 0 0 ? 1 0 0 ??1 0 1 ? 0 1 0 ? ?1 1 0 ? ?0 0 1 ? ?1 0 1 ? ?0 1 1 ? ?1 1 1 (visited[i - 1] = true, pass)

0 0 0 ? 1 0 0 ? 1 1 0 ? 1 1 1 (visited[i - 1] = false, pass)?


Permutation II ?C++ Part 1


Permutation II C++ Part 2

Problem5: Next Permutation II?

Solution:

Dealing with the duplicated numbers. Challenge in place. Similar way to the Permutation I. In finding the second position, we can find from the rightest to left. Once bigger, that is what we want. Swap them and reverse that part.?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末慷吊,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子域携,更是在濱河造成了極大的恐慌措译,老刑警劉巖树枫,帶你破解...
    沈念sama閱讀 212,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件戚啥,死亡現(xiàn)場離奇詭異袒啼,居然都是意外死亡年叮,警方通過查閱死者的電腦和手機(jī)具被,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來只损,“玉大人一姿,你說我怎么就攤上這事≡颈梗” “怎么了叮叹?”我有些...
    開封第一講書人閱讀 158,369評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長爆存。 經(jīng)常有香客問我蛉顽,道長,這世上最難降的妖魔是什么先较? 我笑而不...
    開封第一講書人閱讀 56,799評論 1 285
  • 正文 為了忘掉前任携冤,我火速辦了婚禮,結(jié)果婚禮上闲勺,老公的妹妹穿的比我還像新娘曾棕。我一直安慰自己,他們只是感情好菜循,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評論 6 386
  • 文/花漫 我一把揭開白布翘地。 她就那樣靜靜地躺著,像睡著了一般债朵。 火紅的嫁衣襯著肌膚如雪子眶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,096評論 1 291
  • 那天序芦,我揣著相機(jī)與錄音臭杰,去河邊找鬼。 笑死谚中,一個(gè)胖子當(dāng)著我的面吹牛渴杆,可吹牛的內(nèi)容都是我干的寥枝。 我是一名探鬼主播,決...
    沈念sama閱讀 39,159評論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼磁奖,長吁一口氣:“原來是場噩夢啊……” “哼囊拜!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起比搭,我...
    開封第一講書人閱讀 37,917評論 0 268
  • 序言:老撾萬榮一對情侶失蹤冠跷,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后身诺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蜜托,經(jīng)...
    沈念sama閱讀 44,360評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評論 2 327
  • 正文 我和宋清朗相戀三年霉赡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了橄务。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,814評論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡穴亏,死狀恐怖蜂挪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情嗓化,我是刑警寧澤棠涮,帶...
    沈念sama閱讀 34,509評論 4 334
  • 正文 年R本政府宣布,位于F島的核電站蟆湖,受9級特大地震影響故爵,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜隅津,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評論 3 317
  • 文/蒙蒙 一诬垂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧伦仍,春花似錦结窘、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谓苟,卻和暖如春官脓,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背涝焙。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評論 1 267
  • 我被黑心中介騙來泰國打工卑笨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人仑撞。 一個(gè)月前我還...
    沈念sama閱讀 46,641評論 2 362
  • 正文 我出身青樓赤兴,卻偏偏與公主長得像妖滔,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子桶良,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評論 2 351

推薦閱讀更多精彩內(nèi)容

  • 沒有華麗的辭藻座舍,沒有故意的作態(tài),《看見》這本書如柴靜本人一般真實(shí)陨帆。自上學(xué)起曲秉,便被教導(dǎo)何為正確何為正義,當(dāng)時(shí)頭腦簡單...
    石軒閱讀 228評論 0 0
  • 2017年3月4日星期六 第二次看完《皮囊》 寫在大三 寫在宿舍二樓的自習(xí)室 第二遍 我看得更仔細(xì) 更認(rèn)真 會停下...
    一吃就胖的張好好閱讀 425評論 0 0