标签:style blog color strong io for re c
随机挑选一题试试手气。
问题描述:
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!
杯具。
系统打印出一串非常长的有些变态的测试用例,哎,土办法混不过去啊!
[leetcode笔记] Longest Consecutive Sequence,布布扣,bubuko.com
[leetcode笔记] Longest Consecutive Sequence
标签:style blog color strong io for re c
原文地址:http://www.cnblogs.com/lequ/p/3865845.html