题意:给定一个整数数组,找出数组中最长的连续整数。时间要求是O(n)。
思路:一看时间复杂度要求就想到了hash,第一次先进行初始化操作,时间复杂度为O(n),然后遍历查找,时间复杂度以为O(n),在c++中利用了STL模板unordered_sort,类似于hash。喜欢的同学可以自己查找一下。
代码实现:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = num.size();
if(0 == len)
{
return 0;
}
unordered_set<int> temp;
for(int i = 0; i < len; ++i)
{
temp.insert(num[i]);
}
int ans = 0;
for(int i = 0; i < len; ++i)
{
int cur = num[i];
int cnt = 0;
if(temp.find(cur) != temp.end())
{
temp.erase(cur);
cnt ++;
cnt += getCount(temp, cur + 1, true);
cnt += getCount(temp, cur - 1, false);
ans = max(ans, cnt);
}
}
return ans;
}
int getCount(unordered_set<int> &temp, int num, bool dir)
{
int cnt = 0;
while(temp.find(num) != temp.end())
{
temp.erase(num);
cnt ++;
if(dir)
{
num ++;
}
else
{
num --;
}
}
return cnt;
}
};