10 line O(n) Java solution


  • -1
    K
    public class Solution {
        public int longestConsecutive(int[] nums) {
            TreeSet<Integer> set = new TreeSet<Integer>();
            int current=0,prev = 0,maxLen = 1,currLen = 1;
            for(int i:nums)
               set.add(i);
            prev = set.pollFirst();   
            while(!set.isEmpty()){
                current = set.pollFirst();
                if(current == prev + 1){
                    currLen++;
                    maxLen = Math.max(maxLen,currLen);
                }
                else currLen = 1;
                prev = current;
            }
            return maxLen;
        }
    }
    

Log in to reply
 

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