Easy to understand accepted C# solution


  • 0
    P
    public int LongestConsecutive(int[] nums) {
            if(nums == null)
                return 0;
                
            var map = new HashSet<int>();
            
            foreach(var num in nums)
                if(!map.Contains(num))
                    map.Add(num);
            
            int? val = map.First();
            int curLen = 1;
            int maxLen = 0;
            
            while(val != null)
            {
                map.Remove(val.Value);
                
                int up = val.Value + 1;
                int down = val.Value - 1;
                
                while(map.Contains(up))
                {
                    curLen++;
                    map.Remove(up++);
                }
                
                while(map.Contains(down))
                {
                    curLen++;
                    map.Remove(down--);
                }
                
                if(curLen > maxLen)
                    maxLen = curLen;
                
                if(map.Any())
                {
                    curLen = 1;
                    val = map.First();
                }
                else
                    val = null;
            }
            
            return maxLen;
        }
    

Log in to reply
 

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