首页 > 代码库 > [leetcode笔记] Longest Consecutive Sequence
[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!
杯具。
系统打印出一串非常长的有些变态的测试用例,哎,土办法混不过去啊!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。