1. 程式人生 > >#128 Longest consecutive sequence

#128 Longest consecutive sequence

兩種方法:

  1. 先sort,再找。time complexity: O(nlogn)如果用array記錄次數,space complexity是O(n)。如果只用int來記錄current length以及longest length, space complexity 是O(1)

  2. 用hashset。Time complexity O(n), space complexity O(n).

   public int longestConsecutive(int[] nums) {

       Set<Integer> num_set = new HashSet<Integer>();

       for (int num : nums) {

           num_set.add(num);

       }

 

       int longestStreak = 0;


       for (int num : num_set) {

           if (!num_set.contains(num-1)) {

               int currentNum = num;

               int currentStreak = 1;


               while (num_set.contains(currentNum+1)) {

                   currentNum += 1;

                   currentStreak += 1;

               }


               longestStreak = Math.max(longestStreak, currentStreak);

           }

       }


       return longestStreak;

   }