class Solution { public: int longestConsecutive(vector& nums) { unordered_set s;
//dump all elements into set for(int num : nums){ s.insert(num); }
int ans = 0; for(int num : nums){ //check if previous_element is in set if(s.find(num-1) == s.end()){ int currentElement = num; int count = 1;
//start a chain from current element while(s.find(currentElement+1) != s.end()){ currentElement++; count++; } ans = max(ans, count); } } return ans; } };
It is taking O(NLogN) and time limits exceeds after submitting the code
class Solution {
public:
int longestConsecutive(vector& nums) {
unordered_set s;
//dump all elements into set
for(int num : nums){
s.insert(num);
}
int ans = 0;
for(int num : nums){
//check if previous_element is in set
if(s.find(num-1) == s.end()){
int currentElement = num;
int count = 1;
//start a chain from current element
while(s.find(currentElement+1) != s.end()){
currentElement++;
count++;
}
ans = max(ans, count);
}
}
return ans;
}
};
thanks that helped me understand
what is the time complexity to find an element in set?
Explanation ❤️🌹
can you please write code in java also..
u should have used unordered_set instead of set your's solution T.C is still O(Nlogn) otherwise great explanation
No, it is giving wrong answer with unorderd_set. Why id that so?