Java two set solution, easy to understand


  • 0
    W

    public class Solution {

    public int longestConsecutive(int[] nums) {
        Set<Integer> visited = new HashSet<>();
        Set<Integer> set = new HashSet<>();
        for (int a : nums) {
            set.add(a);
        }
        
        int max = Integer.MIN_VALUE;
        for (int a : nums) {
            if (!visited.contains(a)) {
                int right = a + 1;
                while (set.contains(right)) {
                    visited.add(right++);
                }
                
                int left = a - 1;
                while (set.contains(left)) {
                    visited.add(left--);
                }
                
                max = Math.max(max, right - left - 1);
            } 
        }
        
        return max;
    }
    

    }


Log in to reply
 

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