[leetcode笔记] Longest Consecutive Sequence
随机挑选一题试试手气。
问题描述:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
解题笔记:
(1)第一次Submit
先排个序,再循环遍历一遍,土办法搞起。
1 class Solution { 2 public: 3 int longestConsecutive(vector<int> &num) { 4 //cc_print_int_vector(num); 5 sort(num.begin(), num.end()); 6 //cc_print_int_vector(num); 7 8 int longest = 0; 9 10 int i = 0, j = 0; 11 bool breakFlag = false; 12 for(i = 0; i<num.size() - 1; i++) 13 { 14 for(j = i +1; j<num.size(); j++) 15 { 16 if(num[j-1]+1 != num[j]) 17 { 18 int distance = j - i; 19 if( distance > longest) 20 { 21 longest = distance; 22 } 23 breakFlag = true; 24 break; 25 } 26 } 27 if (breakFlag) 28 { 29 i = j+1; 30 breakFlag = false; 31 continue; 32 } 33 } 34 35 return longest; 36 } 37 };
Submission Result: Time Limit Exceeded!
杯具。
系统打印出一串非常长的有些变态的测试用例,哎,土办法混不过去啊!
(2)第二次Submit
怎么破?题目中有提示,要求必须O(n)复杂度,上面程序中上来就搞了个sort,STL sort的复杂度为O(nlogn),岂不是一下子就超了?不过空间复杂度没有提要求。
俺的第二反应又是土办法搞起,空间换时间。
@#……%#@&……!@%#!&
(冥思苦想了好几天都没有结果)
!@&……@!*……
后来检索了一下,终于找到方法了。[冷汗]
此题要求O(n)复杂度,决定了是不能做排序的,排序至少O(nlogn)复杂度,建map红黑树也不行,构造红黑树其实就相当于做了一遍排序。
只能用哈希表。标准C++中hash表现在名字叫做unordered_set或者unordered_map。
整理清楚思路后,代码一次提交通过。
1 class Solution { 2 public: 3 int longestConsecutive(vector<int> &num) { 4 unordered_map<int, bool> map_num; 5 int longest = 0; 6 int i = 0; 7 8 for (i = 0; i < static_cast<int>(num.size()); ++i) 9 { 10 map_num[num[i]] = true; 11 } 12 13 for (i = 0; i < static_cast<int>(num.size()); ++i) 14 { 15 //search num[i] 16 int search_value = num[i]; 17 unordered_map<int, bool>::iterator it = map_num.find(search_value); 18 if (it == map_num.end()) 19 { 20 continue; 21 } 22 23 int cur_length = 1; 24 25 search_value = num[i] - 1; 26 bool bFound = true; 27 while ( bFound ) 28 { 29 unordered_map<int, bool>::iterator it = map_num.find(search_value); 30 bFound = (it != map_num.end()); 31 if (bFound) 32 { 33 search_value -= 1; 34 cur_length += 1; 35 map_num.erase(it); 36 } 37 else 38 { 39 break; 40 } 41 } 42 43 search_value = num[i] + 1; 44 bFound = true; 45 while ( bFound ) 46 { 47 unordered_map<int, bool>::iterator it = map_num.find(search_value); 48 bFound = (it!=map_num.end()); 49 if (bFound) 50 { 51 search_value += 1; 52 cur_length += 1; 53 map_num.erase(it); 54 } 55 else 56 { 57 break; 58 } 59 } 60 61 if(cur_length>longest) 62 { 63 longest = cur_length; 64 } 65 66 } 67 68 return longest; 69 } 70 };