My Java Solution without considering the duplicate case


  • 0
    C

    import java.util.*;

    public class Solution {

    public int longestConsecutive(int[] nums) {
        Set<Integer> set1 = new HashSet<Integer>();
        Set<Integer> set2 = new HashSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            set1.add(nums[i]);
            set2.add(nums[i]);
        }
        int longest = Integer.MIN_VALUE;
        int count = 1;
        for (int num : set1) {
            int temp1 = num;
            int temp2 = num;
            while (set2.contains(temp1+1)) {
                count++;
                set2.remove(temp1+1);
                temp1++;
            }
            while (set2.contains(temp2-1)) {
                count++;
                set2.remove(temp2-1);
                temp2--;
            }
            set2.remove(num);
            if (longest < count) longest = count;
            count = 1;
        }
        return longest;
    }
    

    }


Log in to reply
 

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