微博上
@陳利人會不定時的發一些程序員的面試題,覺得挺有意思,有時會去寫代碼做一下。最近他開了個微信公眾號:待字閨中 (id: daiziguizhongren),推送這些面試題目和網友的一些好的解答。看到他出的面試題目是促使我開這個博客的另一個重要原因。:)
本文正是關于他出的題目:給一個整數數組,找到其中包含最多連續數的自己,比如給:15,7,12,6,14,13,9,11,則返回5:[11,12,13,14,15]。最簡單的方法是sort然后scan一遍,但是要O(nlgn)。有什么O(n)的方法嗎?
跟他確認了下,對空間復雜度有沒有什么要求,能不能用map這樣的輔助數據結構,他說沒有限制。
我的想法就是,用一個map<int, int>,它的key是一個起始的數字,value是這個起始數字起連續的個數。這樣這個數組遍歷一遍下來,只要map維護好了,自然就能得到最長的連續子串了,并且算法復雜度應該是O(n)。(不考慮map函數實現的復雜度)
前面說了維護好map就可以了,那么怎么來維護這個map呢?
- 取出當前的整數,在map里看一下是否已經存在,若存在則直接取下一個,不存在轉2 (為什么要看是否已經存在,因為題目沒有說不會有重復的數字。)
- 查看下map里面當前數字的前一個是否存在,如果存在,當前的最長長度就是前一個最長長度+1
- 查看下map里面當前數字的后一個是否存在,如果存在,那么就將以下一個數字開始的子串的最后一個更新下,因為本來沒有連上的2個子串,因為當前數字的出現連起來了
- 接著再看下前面數字是否存在,如果存在,就更新以這個數字結尾的子串的第一個數字的連續子串長度,原因同上
算法就是如上所示了,我們拿例子演練一遍
1) 首先給定15,這個時候map里面沒有15也沒有14和16,那么這個執行完了之后map是map[15] = 1;
2) 然后遇到7,同上,也沒有6,7和8,所以執行玩了之后變成map[7]=1, map[15]=1;
3) 12同上,map[7]=1, map[12]=1, map[15]=1;
4) 接下來是6,6就不一樣了,因為7存在的,所以執行上面第3步之后,map[6]=2,map[7]=2,map[12]=1,map[15]=1;
5) 14的情況跟6一樣,結果是map[6]=2,map[7]=2,map[12]=1,map[14]=2,map[15]=2;
6) 13的情況相對復雜一些,因為12和14都存在了 ,所以它會執行以上1,2,3,4的所有4步:首先12存在,所以13的最長子串是2,14存在,所以會更新到14起始的最后一個數字的最長長度,這里就是15的長度=它自己的加上13的長度,也就是4,同時我們把13的長度也改成4,最后因為12存在,我們要更新以12結尾的連續子串的開始處,本例中就是12自己,12對應更新成4
7) 最后是11,11的前面一個數字不存在,后一個數字存在,也就是要執行以上1,3,第3步結束的時候已經是11和15都更新成5了。最后的結果也就是5,并且是從11起始的。
下面上代碼:
1 int find_longest_consecutive_items(int *list, int size) {
2 map<
int,
int> mapping;
3 int max = 0;
4 // The start point for the longest chain
5 int start = 0;
6
7 for (
int i=0; i<size; i++) {
8 if (mapping.find(list[i]) == mapping.end()) {
9 int cur = list[i];
10 // Set current position as the start point for this potential longest chain
11 int cur_start = cur;
12 mapping.insert(make_pair(cur, 1));
13
14 map<
int,
int>::iterator prev = mapping.find(cur - 1);
15 map<
int,
int>::iterator next = mapping.find(cur + 1);
16
17 if (prev != mapping.end()) {
18 // If previous number exists, increase current consecutive count
19 mapping[cur] = prev->second + 1;
20 }
21
22 if (next != mapping.end()) {
23 // Update the last one in the chain with the consecutive count from the one before current position
24 int last = next->first + next->second - 1;
25 mapping[last] = mapping[cur] = mapping[cur] + mapping[last];
26 }
27
28 if (prev != mapping.end()) {
29 // Update the first one in the chain with the consecutive count from the one after current position
30 int first = prev->first - prev->second + 1;
31 mapping[first] = mapping[cur];
32
33 // Use the first one as the start point for the whole chain
34 cur_start = first;
35 }
36
37 if (mapping[cur_start] > max) {
38 start = cur_start;
39 max = mapping[cur_start];
40 }
41 }
42 }
43
44 cout << "Longest consecutive items:";
45 for (
int i=0; i<max; i++) {
46 cout << " " << start + i;
47 }
48 cout << endl;
49
50 return max;
51 }
完整代碼