128. Longest Consecutive Sequence

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

題解:

在一個未排序的數組當中,找到最長的遞增子序列,而這個子序列的遞增的差為1,再找到最長子序列後,輸出它的長度。

例如:

[100,4,200,1,3,2] ->[1,2,3,4] 輸出4

而在這一題中,需要O(n)的時間複雜度。

題解:

因為這一題是需要O(n)的時間複雜度,故排序方法可以先捨去了,必須用其他方法來解這道題。

1.利用Set來存儲數組的集合,例如:

set = {100, 4, 200, 1, 3, 2}

  並利用一個max_lcs_length來存儲最大長度

2.歷遍給定的數組

3.在歷遍數組的過程中,將可能相鄰的左右數字都枚舉一遍,若在集合中有便刪除,沒有則跳出

把從左邊的連續數組全部找出,並從集合中刪除(表示已經使用過了),並記錄目前長度

ex: cur = 3

set = 1 3 2 100 4 count = 1

set = 3 100 4     count = 3


把從右邊的連續數組全部找出,並從集合中刪除(表示已經使用過了),並記錄目前長度

ex: cur = 3

set = 1 3 2 100 4 count = 1

set = 1 3 2 100   count = 2

  4.最大長度與目前長度進行比較,更新最大長度

package LeetCode.Hard;

import java.util.HashSet;
import java.util.Set;

public class LongestConsecutiveSequence {
    public int longestConsecutive(int[] nums) {
        if(nums.length == 0) {
            return 0;
        }
        
        //這個set是用來存儲所有數字的集合
        Set<Integer> set = new HashSet<Integer>();
        
        //把所有數字加入set當中
        for(int num : nums) {
            set.add(num);
        }
        
        //默認lcs_max=1(因為lcs最短為1)
        int lcs_max = 1;
        
        //歷遍數組中每個數字
        for(int num : nums) {
            //滿足題目要求 1(left) 2 3(左邊比目前少1)
            int left = num - 1;
            
            //滿足題目要求 1 2 3(right)(右邊比目前多1)
            int right = num + 1;
            
            //目前lcs的數量
            int lcs_count = 1;
            
            //把從左邊的連續數組全部找出,並從集合中刪除(表示已經使用過了)
            /* ex: cur = 3
             *     set = 1 3 2 100 4 count = 1
                   set = 3 100 4     count = 3
            */
            while(set.contains(left)) {
                lcs_count ++;
                set.remove(left);
                left --;
            }
                
            //把從右邊的連續數組全部找出,並從集合中刪除(表示已經使用過了)
            /*ex: cur = 3
             *    set = 1 3 2 100 4 count = 1
                  set = 1 3 2 100   count = 2
            */
            while(set.contains(right)) {
                lcs_count ++;
                set.remove(right);
                right ++;
            }    
            
            lcs_max = Math.max(lcs_count, lcs_max);
        }
        
        return lcs_max;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值