Clean Java code, same O(n) idea with others, beats 90%.


  • 2
    S
    public class Solution {
    public int longestConsecutive(int[] nums) {
        
        Set<Integer> set = new HashSet<Integer>();
        
        for(int n: nums) set.add(n);
        
        int max = 0;
        
        for(int n: nums){
            int count = 0;
            if(set.isEmpty()) break;
            
            int val = n;
            while(set.remove(val--))
                count ++;
            
            val = n;
            while(set.remove(++val))
                count ++;
            
            max = Math.max(count,max);
        }
        
        return max;
    
        }
    

    }


  • 3
    B

    Every time I look at discussion I feel like an idiot.


  • 0
    E

    Erase element in Set it's work O(logN) ur code doesn't work at O(n), In the bad case work O(NlogN)


  • 0
    T
    This post is deleted!

  • 0
    I

    @ELDVN
    Hi! I just wondering why erase element in Set would cost O(nlogn) time? I checked the document which says the HashSet provides constant time performance for add, remove, contains and size operations. Can you give more explanations?
    Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.