简单的做图网站,哈尔滨做平台网站平台公司吗,支持微信打开的wordpress,没有初中毕业证怎么提升学历题目
给定一个未排序的整数数组 nums #xff0c;找出数字连续的最长序列#xff08;不要求序列元素在原数组中连续#xff09;的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
思路
哈希表#xff08;unordered_set#xff09;存数组#xff0c;遍历哈…题目
给定一个未排序的整数数组 nums 找出数字连续的最长序列不要求序列元素在原数组中连续的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
思路
哈希表unordered_set存数组遍历哈希表遍历到x查看x-1是否存在于哈希表中存在即略过该元素存在的话它会被x-1记录。若不存在即查看哈希表中是否有x1且重复直到没有x1,更新最长连续序列。
代码
class Solution {
public:int longestConsecutive(vectorint nums) {unordered_setintst;unordered_setint::iterator it,it2;st.clear();int ans0;for(int i0;inums.size();i){st.insert(nums[i]);}for(itst.begin();it!st.end();it){if(st.find(*it-1)st.end()){int num0;it2 st.find(*it1);while(it2!st.end()){num1;itit2;it2 st.find(*it1);}if(ansnum){ansnum;}}}return ans;}
};