鱼C论坛

 找回密码
 立即注册
查看: 2285|回复: 0

[学习笔记] leetcode 128. Longest Consecutive Sequence

[复制链接]
发表于 2019-10-2 06:39:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

  2. Your algorithm should run in O(n) complexity.

  3. Example:

  4. Input: [100, 4, 200, 1, 3, 2]
  5. Output: 4
  6. Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
复制代码


using priorityqueue

  1. class Solution {
  2.     public int longestConsecutive(int[] nums) {
  3.         if(nums.length == 0) return 0;
  4.         if(nums.length == 1) return 1;
  5.         
  6.         PriorityQueue<Integer> queue = new PriorityQueue<>();
  7.         for(int i : nums) queue.offer(i);
  8.         int max = Integer.MIN_VALUE;
  9.         int count = 1;
  10.         while(queue.size() > 1){
  11.             int head = queue.poll();
  12.             if(head == queue.peek() -1) count ++;
  13.             else if (head == queue.peek()) continue;
  14.             else count =1;
  15.             
  16.             if(count > max) max= count;
  17.             
  18.         }
  19.         
  20.         if(max == Integer.MIN_VALUE) return count;
  21.         else return max;
  22.     }
  23. }
复制代码



sort array!
  1. class Solution {
  2.     public int longestConsecutive(int[] nums) {
  3.         if(nums.length == 0) return 0;
  4.         if(nums.length == 1) return 1;
  5.         
  6.         Arrays.sort(nums);
  7.         int max = Integer.MIN_VALUE;
  8.         int count = 1;
  9.         for(int i = 1; i< nums.length; i++){
  10.             if(nums[i] != nums[i-1]){
  11.                 if(nums[i] - nums[i-1] == 1){
  12.                     count++;
  13.                 }else{
  14.                     max = Math.max(max,count);
  15.                     count =1;
  16.                 }
  17.             }
  18.             
  19.             
  20.         }
  21.         
  22.         return Math.max(max,count);
  23.     }
  24. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 17:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表