码迷,mamicode.com
首页 > 其他好文 > 详细

#128 Longest consecutive sequence

时间:2018-11-10 15:29:52      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:max   dir   str   tco   com   nlog   +=   turn   hash   

两种方法:

  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;

   }

#128 Longest consecutive sequence

标签:max   dir   str   tco   com   nlog   +=   turn   hash   

原文地址:https://www.cnblogs.com/yxcindy/p/9938764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!