Showing posts with label Lintcode. Show all posts
Showing posts with label Lintcode. Show all posts

Sunday, July 19, 2015

Sliding Window Median @Lintcode

Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. )

For array [1,2,7,8,5], moving window size k = 3. return [2,7,7]
At first the window is at the start of the array like this
[ | 1,2,7 | ,8,5] , return the median 2;
then the window move one step forward.
[1, | 2,7,8 | ,5], return the median 7;
then the window move one step forward again.
[1,2, | 7,8,5 | ], return the median 7;

提示里面说到O(nlgn)的复杂度,加上求median,很自然地会想到用heap。关于如何用两个堆track中位数很多文章里都有解释。问题是heap不支持random remove操作,如果自己实现会比较麻烦。java中PriorityQueue是支持random remove的,所以就偷懒使用了;如果在面试中可以自己解释如何实现这个机制。
根据题意,median总是取N/2向下取整的,所以只要一直保持maxheap的size不小于minheap的size,这样每次只要取maxheap的堆顶。
另外要注意的是每次remove之后可能会造成两个heap的size不平衡,所以要重新resize

Copy Books @Lintcode

Given an array A of integer with size of n( means n books and number of pages of each book) and k people to copy the book. You must distribute the continuous id books to one people to copy. (You can give book A[1],A[2] to one people, but you cannot give book A[1], A[3] to one people, because book A[1] and A[3] is not continuous.) Each person have can copy one page per minute. Return the number of smallest minutes need to copy all the books.

Example
Given array A = [3,2,4], k = 2.
Return 5( First person spends 5 minutes to copy book 1 and book 2 and second person spends 4 minutes to copy book 3. )
很明显地用dp来做。dp[i][j] 代表前i本书由j个工作者完成需要的最小时间。状态转移方程如下:
dp[i+1][j+1] = Min(Max(dp[i][k], A[k]+...+A[j+1])),  where k from i to j+1
意思就是每加入一个新worker的时候,从后往前累加他需要copy的book,每次更新总体所需要的时间;而总体需要的时间是之前所有worker分配方案中的最优时间和新worker所需时间两者中的较大值。

时间复杂度 O(N^2*k), 暂时没想到 O(N*k) 的方法 :( 麻烦各路大神指点。。。

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...