锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
鏈枃姝f槸鍏充簬浠栧嚭鐨勯鐩細緇欎竴涓暣鏁版暟緇勶紝鎵懼埌鍏朵腑鍖呭惈鏈澶氳繛緇暟鐨勮嚜宸憋紝姣斿緇欙細15錛?錛?2錛?錛?4錛?3錛?錛?1錛屽垯榪斿洖5:[11,12,13,14,15]銆傛渶綆鍗曠殑鏂規硶鏄痵ort鐒跺悗scan涓閬嶏紝浣嗘槸瑕丱(nlgn)銆傛湁浠涔圤(n)鐨勬柟娉曞悧錛?br />
璺熶粬紜浜嗕笅錛屽絀洪棿澶嶆潅搴︽湁娌℃湁浠涔堣姹傦紝鑳戒笉鑳界敤map榪欐牱鐨勮緟鍔╂暟鎹粨鏋勶紝浠栬娌℃湁闄愬埗銆?br />
鎴戠殑鎯蟲硶灝辨槸錛岀敤涓涓猰ap<int, int>錛屽畠鐨刱ey鏄竴涓搗濮嬬殑鏁板瓧錛寁alue鏄繖涓搗濮嬫暟瀛楄搗榪炵畫鐨勪釜鏁般傝繖鏍瘋繖涓暟緇勯亶鍘嗕竴閬嶄笅鏉ワ紝鍙map緇存姢濂戒簡錛岃嚜鐒跺氨鑳藉緱鍒版渶闀跨殑榪炵畫瀛愪覆浜嗭紝騫朵笖綆楁硶澶嶆潅搴﹀簲璇ユ槸O(n)銆傦紙涓嶈冭檻map鍑芥暟瀹炵幇鐨勫鏉傚害錛?br />
鍓嶉潰璇翠簡緇存姢濂絤ap灝卞彲浠ヤ簡錛岄偅涔堟庝箞鏉ョ淮鎶よ繖涓猰ap鍛紵
綆楁硶灝辨槸濡備笂鎵紺轟簡錛屾垜浠嬁渚嬪瓙婕旂粌涓閬?br />
1) 棣栧厛緇欏畾15錛岃繖涓椂鍊檓ap閲岄潰娌℃湁15涔熸病鏈?4鍜?6錛岄偅涔堣繖涓墽琛屽畬浜嗕箣鍚巑ap鏄痬ap[15] = 1;
2) 鐒跺悗閬囧埌7錛屽悓涓婏紝涔熸病鏈?錛?鍜?錛屾墍浠ユ墽琛岀帺浜嗕箣鍚庡彉鎴恗ap[7]=1, map[15]=1;
3) 12鍚屼笂錛宮ap[7]=1, map[12]=1, map[15]=1;
4) 鎺ヤ笅鏉ユ槸6錛?灝變笉涓鏍蜂簡錛屽洜涓?瀛樺湪鐨勶紝鎵浠ユ墽琛屼笂闈㈢3姝ヤ箣鍚庯紝map[6]=2,map[7]=2,map[12]=1,map[15]=1;
5) 14鐨勬儏鍐佃窡6涓鏍鳳紝緇撴灉鏄痬ap[6]=2,map[7]=2,map[12]=1,map[14]=2,map[15]=2;
6) 13鐨勬儏鍐電浉瀵瑰鏉備竴浜涳紝鍥犱負12鍜?4閮藉瓨鍦ㄤ簡 錛屾墍浠ュ畠浼氭墽琛屼互涓?錛?錛?錛?鐨勬墍鏈?姝ワ細棣栧厛12瀛樺湪錛屾墍浠?3鐨勬渶闀垮瓙涓叉槸2錛?4瀛樺湪錛屾墍浠ヤ細鏇存柊鍒?4璧峰鐨勬渶鍚庝竴涓暟瀛楃殑鏈闀塊暱搴︼紝榪欓噷灝辨槸15鐨勯暱搴?瀹冭嚜宸辯殑鍔犱笂13鐨勯暱搴︼紝涔熷氨鏄?錛屽悓鏃舵垜浠妸13鐨勯暱搴︿篃鏀規垚4錛屾渶鍚庡洜涓?2瀛樺湪錛屾垜浠鏇存柊浠?2緇撳熬鐨勮繛緇瓙涓茬殑寮濮嬪錛屾湰渚嬩腑灝辨槸12鑷繁錛?2瀵瑰簲鏇存柊鎴?
7) 鏈鍚庢槸11錛?1鐨勫墠闈竴涓暟瀛椾笉瀛樺湪錛屽悗涓涓暟瀛楀瓨鍦紝涔熷氨鏄鎵ц浠ヤ笂1錛?錛岀3姝ョ粨鏉熺殑鏃跺欏凡緇忔槸11鍜?5閮芥洿鏂版垚5浜嗐傛渶鍚庣殑緇撴灉涔熷氨鏄?錛屽茍涓旀槸浠?1璧峰鐨勩?br />
涓嬮潰涓婁唬鐮侊細
1 int find_longest_consecutive_items(int *list, int size) {
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 }
瀹屾暣浠g爜
]]>