#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;

   }

猜你喜欢

转载自www.cnblogs.com/yxcindy/p/9938764.html