Java iterative O(N) solution with HashSet


  • 0
    I
    public class Solution {
        public int longestConsecutive(int[] nums) {
            
            HashSet<Integer> data = new HashSet<Integer>();
            for(int a : nums) {
                data.add(a);
            }
            
            int len = 0;
            while(!data.isEmpty()) {
                int a = data.iterator().next();
                data.remove(a);
                
                int up = a + 1;
                int down = a - 1;
                int count = 1;
                
                while(data.contains(down)) {;
                    data.remove(down);
                    count++;
                    down--;
                }
                while(data.contains(up)) {
                    data.remove(up);
                    count++;
                    up++;
                }
                
                if(len < count) {
                    len = count;
                }
            }
            
            return len;
        }
    }
    

Log in to reply
 

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