128. Longest Consecutive Sequence

来源:互联网 发布:淘宝女装拍照技巧 编辑:程序博客网 时间:2024/06/14 07:20

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

原创粉丝点击